<?php

class stFacebookToolboxController extends stcontroller_2_1 {

    public function __construct($config) {
        parent::__construct($config);  
        if(is_admin()){
            $this->config = $this->functions->setAmazonConfig($this->config);
        }
    }

    public function setConfig($config) {
        $this->config = $config;
        if ($this->actionName == "index") {
            $this->actionName = $config ['default_action'];
        }

        $this->config ['classDir'] = $this->config ['pluginDir'] . 'libs/2.1/classes/';
        $this->config ['classPath'] = $this->config ['pluginPath'] . 'libs/2.1/classes/';
        $this->config ['backendCss'] = $this->config ['pluginPath'] . 'css/backend/';
        $this->config ['backendScript'] = $this->config ['pluginPath'] . 'scripts/backend/';
        $this->config ['frontendCss'] = $this->config ['pluginPath'] . 'css/frontend/';
        $this->config ['frontendScript'] = $this->config ['pluginPath'] . 'scripts/frontend/';
        $this->config ['imagesUrl'] = $this->config ['pluginPath'] . 'images/';
        $this->config['months'][1] = "January";
        $this->config['months'][2] = "February";
        $this->config['months'][3] = "March";
        $this->config['months'][4] = "April";
        $this->config['months'][5] = "May";
        $this->config['months'][6] = "June";
        $this->config['months'][7] = "July";
        $this->config['months'][8] = "August";
        $this->config['months'][9] = "September";
        $this->config['months'][10] = "October";
        $this->config['months'][11] = "November";
        $this->config['months'][12] = "December";
        $this->config['font'] = 'Playfair+Display|Limelight|Maven+Pro|Muli|Tenor+Sans|Brawler|Carter+One|Wire+One|Nunito|Podkova|The+Girl+Next+Door|Ruslan+Display|Jura|Caudex|Waiting+for+the+Sunrise|Shanti|Metrophobic|Play|Rokkitt|Ultra|Wallpoet|Paytone+One|Francois+One|Didact+Gothic|Judson|Mako|Sigmar+One|Megrim|Holtwood+One+SC|Over+the+Rainbow|Monofett|News+Cycle|Bigshot+One|Smythe|Special+Elite|Miltonian|Kreon|Open+Sans|Oswald|Vibur|Nova|Michroma|Indie+Flower|Meddon|Droid+Sans+Mono|Pacifico|Quattrocento+Sans|Amaranth|Annie+Use+Your+Telescope|Bangers|Coming+Soon|Expletus+Sans|Terminal+Dosis+Light|UnifrakturCook|Tangerine|MedievalSharp|Sniglet|Dancing+Script|Astloch|Cabin+Sketch|Quattrocento|Sunshiney|Kenia|Chewy|Old+Standard+TT|Calligraffitti|Arvo|PT+Serif|Anton|Orbitron|Schoolbell|PT+Sans|Corben|IM+Fell|Just+Another+Hand|Architects+Daughter|Rock+Salt|UnifrakturMaguntia|Syncopate|Goudy+Bookletter+1911|Bentham|Puritan|Irish+Grover|Crafty+Girls|Cherry+Cream+Soda|Permanent+Marker|Radley|Allerta|Kristi|League+Script|Crushed|Kranky|Neuton|Yanone+Kaffeesatz|Vollkorn|Maiden+Orange|Neucha|Reenie+Beanie|Slackey|Homemade+Apple|Cousine|Lekton|Arimo|Josefin+Sans|Mountains+of+Christmas|Luckiest+Guy|Copse|Droid+Serif|Cardo|Geo|Cantarell|Raleway|Gruppo|Allerta+Stencil|EB+Garamond|Unkempt|Cuprum|Ubuntu|Droid+Sans|Dawning+of+a+New+Day|Molengo|Lobster|Anonymous+Pro|Merriweather|Six+Caps|Nobile|Inconsolata|Allan|Cabin|Covered+By+Your+Grace|OFL+Sorts+Mill+Goudy+TT|Tinos|Josefin+Slab|Bevan|Philosopher|Buda|Lato|Damion|Fontdiner+Swanky|Coda|Sue+Ellen+Francisco|Crimson+Text|VT323|Aclonica|Candal|Walter+Turncoat|Just+Me+Again+Down+Here|Swanky+and+Moo+Moo';
    }

    public function loadAdminCss() { // load more css custom here
        echo "<link rel='stylesheet' href='" . $this->config['backendCss'] . "stFaceBookToolBox.css' type='text/css' media='all' />";
        echo "<link rel='stylesheet' href='" . $this->config['backendCss'] . "form.css' type='text/css' media='all' />";
        echo "<link rel='stylesheet' href='" . $this->config['backendCss'] . "colorpicker.css' type='text/css' media='all' />";
        echo "<link rel='stylesheet' href='" . $this->config['backendCss'] . "prettyPhoto.css' type='text/css' media='all' />";
        echo "<link rel='stylesheet' href='" . $this->config['backendCss'] . "imgareaselect-default.css' type='text/css' media='all' />";
        echo '<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=' . $this->config['font'] . '" />';
    }

    public function loadAdminScript() { // load more js custom here
        echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . 'stFacebookToolboxcustom.js"></script>';
        echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . 'jquery.colorPicker.js"></script>';
        echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . 'colorpicker.js"></script>';
        echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . 'eye.js"></script>';
//    	echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . 'layout.js"></script>';
        echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . 'utils.js"></script>';
        echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . 'jquery.prettyPhoto.js"></script>';
        echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . 'jquery.imgareaselect.pack.js"></script>';
        echo '<script type="text/javascript" src="http://www.google.com/jsapi"></script>';
        echo '<script src="http://connect.facebook.net/en_US/all.js"></script>';
        echo '<script type="text/javascript">
            google.load("visualization", "1", {packages:["corechart"]});
        </script>';
        wp_enqueue_script('common');
        wp_enqueue_script('jquery-color');
        wp_admin_css('thickbox');
        wp_print_scripts('post');
        wp_print_scripts('media-upload');
        wp_print_scripts('jquery');
        wp_print_scripts('jquery-ui-core');
        wp_print_scripts('jquery-ui-tabs');
        wp_print_scripts('tiny_mce');
        wp_print_scripts('editor');
        wp_print_scripts('editor-functions');
        wp_print_scripts('wplink');
        wp_print_styles('wplink');
        add_thickbox();
        wp_tiny_mce();
        wp_admin_css();
        wp_enqueue_script('utils');
    }
    
    public function customAdminEnqueueScript() {
        parent::customAdminEnqueueScript();
        wp_enqueue_script('common');
        wp_enqueue_script('jquery-color');
        wp_enqueue_script('utils');
    }
    public function loadAdminGlobalScript() {
       
    }

    public function loadCss() {
        //this is function import javascript
        parent::loadCss();
    }

    public function loadScript() {
        //this is function import javascript
        parent::loadScript();
    }

    public function activationPlugin() {
        // put your activation code here
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $option['facebook_like_setting'] = array(
            'style' => 'standard',
            'faces' => 'true',
            'width' => '450',
            'height' => '80',
            'font' => '',
            'colorscheme' => 'light',
            'verb' => 'like',
            'post' => '1',
            'up' => '1',
            'pront' => 'true',
            'archive' => 'true',
            'categories' => 'true',
            'mode' => 'var',
            'permision' => 'administrator',
            'user' => '1');
        //update_option('facebook_like_setting',$options);

        $option['facebook_graph'] = array(
            'title' => '',
            'type' => 'athlete',
            'image' => '',
            'image2' => '',
            'site_name' => '',
            'description' => '',
            'admins' => '',
            'app_id' => '',
            'user' => '1',
            'contact' => '1',
            'email' => '',
            'phone_number' => '',
            'fax_number' => '',
            'latitude' => '',
            'longitude' => '',
            'street-address' => '',
            'locality' => '',
            'region' => '',
            'postal-code' => '',
            'country-name' => '',
            'location' => '1'
        );
        //update_option('facebook_graph',$graph);
        $option['facebook_dashboard'] = array('1', '2', '3');
        $this->updateOption($option);
        $wpdb->query("CREATE TABLE IF NOT EXISTS `st_likepluginstatistics` (`id` int(3) NOT NULL AUTO_INCREMENT,`url` text COLLATE utf8_unicode_ci NOT NULL,`user_id` INT NOT NULL,`share_count` int(3) NOT NULL,`site_id` INT NOT NULL,`like_count` int(3) NOT NULL,`comment_count` int(3) NOT NULL,`click_count` int(3) NOT NULL,`date` VARCHAR( 11 ) NOT NULL,total_like INT(11) NOT NULL,PRIMARY KEY (`id`))");
        $wpdb->query("CREATE  TABLE IF NOT EXISTS `st_likepluginhistory`(`historyid` INT NOT NULL AUTO_INCREMENT ,  `date` VARCHAR(11) ,  `likes` INT NOT NULL ,  `shares` INT NOT NULL ,  `comments` INT NOT NULL ,  `clicks` INT NOT NULL ,  PRIMARY KEY (`historyid`) )ENGINE = InnoDB");
        $wpdb->query("CREATE  TABLE IF NOT EXISTS `st_likepluginfbpagelist` (`pageid` VARCHAR(255) NOT NULL ,`user_id` INT(11) NOT NULL,`pagename` VARCHAR(150) NULL ,`pagepictureurl` TEXT NULL ,`pageurl` TEXT NULL ,`fancount` INT NULL,`get_fan` TEXT NULL ,PRIMARY KEY (`pageid`) )ENGINE = InnoDB");
        $wpdb->query("CREATE  TABLE IF NOT EXISTS `st_likepluginfbpagestatistics` (`statiisticsid` INT NOT NULL AUTO_INCREMENT ,`facebookpageid` BIGINT NOT NULL ,`date` varchar(11) NOT NULL ,`numberofposts` INT NULL ,`numberofcomments` INT NULL ,`numberoflikes` INT NULL ,`numberofshares` INT NULL ,`numberofusers` INT NULL ,`fancount` INT NULL,`user_id` INT NOT NULL ,PRIMARY KEY (`statiisticsid`) )ENGINE = InnoDB");
        $wpdb->query("CREATE TABLE IF NOT EXISTS `st_likepluginfbusers` (`uid` bigint(20) NOT NULL COMMENT 'The Facebook UserID',`user_id` INT(11) NOT NULL,`birthday` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,`currentlocation` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,`firstname` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,`lastname` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,`locale` varchar(2) COLLATE utf8_unicode_ci DEFAULT NULL,`profileurl` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,`sex` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,`timezone` int(11) DEFAULT NULL, PRIMARY KEY (`uid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;");
        $wpdb->query("CREATE  TABLE IF NOT EXISTS `st_likepluginfbtypes` (`typeid` INT NOT NULL AUTO_INCREMENT ,`facebooktype` INT(45) NOT NULL ,PRIMARY KEY (`typeid`) )ENGINE = InnoDB");
        $wpdb->query("CREATE  TABLE IF NOT EXISTS `fbt_flagtypes` (`flagtypeid` INT NOT NULL AUTO_INCREMENT ,`user_id` INT(11) NOT NULL,`flagname` VARCHAR(45) NOT NULL ,`flagcolorcode` VARCHAR(7) NOT NULL ,`flagdescription` VARCHAR(500) NULL ,PRIMARY KEY (`flagtypeid`))");
        $wpdb->query("INSERT INTO `st_likepluginfbtypes` (`typeid` ,`facebooktype`)VALUES (NULL , 'Status'), (NULL , 'Link'), (NULL , 'Photo'), (NULL , 'Video'), (NULL , 'Post'), (NULL , 'Unknown');");
        $wpdb->query("CREATE TABLE IF NOT EXISTS `st_likepluginfbmessages` (`messageid` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,`user_id` INT(11) NOT NULL,`searchtermid` int(11) NOT NULL,`fromuserid` bigint(20) NOT NULL,`messagetypeid` varchar(25) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,`messagetext` text CHARACTER SET utf8 COLLATE utf8_unicode_ci,`picture` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,`link` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,`source` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,`icon` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,`createdtime` datetime DEFAULT NULL,`updatedtime` datetime DEFAULT NULL,`date` varchar(11) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,`likes` int(11) DEFAULT NULL,`flagtypeid` int(11) NOT NULL,PRIMARY KEY (`messageid`))");
        $wpdb->query("CREATE  TABLE IF NOT EXISTS `st_likepluginsearchterms` (`searchtermid` INT NOT NULL AUTO_INCREMENT ,`user_id` INT(11) NOT NULL,`searchterm` VARCHAR(45) NOT NULL ,PRIMARY KEY (`searchtermid`) )ENGINE = InnoDB");
        $wpdb->query("CREATE TABLE IF NOT EXISTS `st_facebook_feed` (`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,`post_id` INT NOT NULL ,`likes` INT NOT NULL, `ip` VARCHAR( 255 ) NOT NULL ,`cdate` VARCHAR( 11 ) NOT NULL) ENGINE = MYISAM ;");
        $wpdb->query("CREATE  TABLE IF NOT EXISTS `st_fanofpage` (`fanofpageid` INT NOT NULL AUTO_INCREMENT ,  `fanuserid` VARCHAR(255) NOT NULL ,`pageid` VARCHAR(255) NOT NULL ,user_id INT NOT NULL,PRIMARY KEY (`fanofpageid`))");
        $wpdb->query("CREATE TABLE `st_sitemap` (`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,`site_name` VARCHAR( 255 ) NOT NULL ,`site_url` TEXT NOT NULL ,`user_id` INT NOT NULL ,`number` BIGINT NOT NULL)");
        $wpdb->query("CREATE TABLE `st_sitemap_link` (`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,`user_id` INT NOT NULL ,`site_id` INT NOT NULL ,`link` TEXT NOT NULL)");
        $wpdb->query("CREATE TABLE `st_facebookimagemap` (`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,`begin` VARCHAR( 255 ) NOT NULL ,`end` VARCHAR( 255 ) NOT NULL ,`width` INT NOT NULL,`height` INT NOT NULL,`title` TEXT NOT NULL ,`link` TEXT NOT NULL,`user_id` INT NOT NULL)");
        $wpdb->query("CREATE TABLE `st_fbuser_relation` (`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY  ,`system_user_id` INT NOT NULL ,`facebook_user_id` BIGINT NOT NULL)");
//`bucket_id` int(11) NOT NULL,
        $table = $wpdb->prefix . "st_postcard_card";
        $structure = "CREATE TABLE IF NOT EXISTS $table (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `smt_user_id` int(11) NOT NULL,
              `bucket_name` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              `folder_name` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              `template_id` int(11) NOT NULL DEFAULT '0',
              `cat_id` int(11) NOT NULL,
              `name` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              `logo_file` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              `file_name` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              `thumb_url` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              `url` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              `back_card_file_name` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              `back_thumb_url` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              `back_url` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              `description` text COLLATE utf8_unicode_ci,
              `back_card_text` text COLLATE utf8_unicode_ci,
              `num_faces` int(11) NOT NULL DEFAULT '1',
              `faces` text COLLATE utf8_unicode_ci,
              `ip_creator` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              `photographer` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              `featured` SMALLINT NOT NULL DEFAULT '0',
              `priority` INT( 11 ) NULL,
              `cdate` datetime NOT NULL,              
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ;
        ";
        dbDelta($structure);

        $table = $wpdb->prefix . "st_postcard_user";
        $structure = "CREATE TABLE IF NOT EXISTS $table (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `smt_user_id` int(11) NOT NULL,
              `fb_user_id` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              `password` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              `name` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              `email` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              `cdate` datetime NOT NULL,              
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ;
        ";
        dbDelta($structure);

        $table = $wpdb->prefix . "st_postcard_share";
        $structure = "CREATE TABLE IF NOT EXISTS $table (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `card_id` int(11) NOT NULL,
              `ip_share` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              `type_share` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              `number_share` int(11) NOT NULL DEFAULT '1',
              `meta_share` text COLLATE utf8_unicode_ci,
              `cdate` datetime NOT NULL,              
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ;
        ";
        dbDelta($structure);

        $table = $wpdb->prefix . "st_postcard_view";
        $structure = "CREATE TABLE IF NOT EXISTS $table (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `card_id` int(11) NOT NULL,
              `ip_view` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              `number_view` int(11) NOT NULL DEFAULT '1',
              `cdate` datetime NOT NULL,              
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ;
        ";
        dbDelta($structure);

        $table = $wpdb->prefix . "st_postcard_category";
        $structure = "CREATE TABLE IF NOT EXISTS $table (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `smt_user_id` int(11) NOT NULL,
              `title` varchar(225) COLLATE utf8_unicode_ci NOT NULL,
              `description` text COLLATE utf8_unicode_ci,
              `cdate` datetime NOT NULL,              
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ;
        ";
        dbDelta($structure);
    }

    public function deactivationPlugin() {
        // put your deactivation code here
    }

    public function cronjob_statistics() {
        $options = $this->option;
        $option = $options['facebook_like_setting'];
        global $wpdb;
        //--------
        if ($option['user'] == '1') {
            $offset = 0;
            $rowsPerPage = 50;
            $count = $wpdb->get_var("SELECT count(ID) FROM wp_posts WHERE post_status='publish'");
            $data['shares'] = 0;
            $data['likes'] = 0;
            $data['comments'] = 0;
            $data['clicks'] = 0;
            while ($offset < $count) {
                $result = $wpdb->get_results("SELECT * FROM wp_posts WHERE post_status='publish' LIMIT $offset, $rowsPerPage");
                foreach ($result as $row) {
                    $array[] = urlencode(get_permalink($row->ID));
                }
                $string = implode(",", $array);
                $xml = simplexml_load_file('http://api.facebook.com/restserver.php?method=links.getStats&urls=' . $string, NULL, LIBXML_NOBLANKS);
                foreach ($xml->link_stat as $x) {
                    if ($x->url != '0') {
                        $data['shares'] += $x->share_count;
                        $data['likes'] += $x->like_count;
                        $data['comments'] += $x->comment_count;
                        $data['clicks'] += $x->click_count;
                    }
                }
                $xml = array();
                $array = array();
                $offset = $offset + $rowsPerPage;
            }
            $time = mktime();
            $last = intval($time) - 24 * 3600;
            $day = date('d-m-Y', $last);
            $count = count($wpdb->get_results("SELECT * FROM st_likepluginhistory WHERE date='" . $day . "'"));
            if ($count == 0) {
                $data['date'] = $day;
                $type = array('%d', '%d', '%d', '%d', '%s');
                $wpdb->insert('st_likepluginhistory', $data, $type);
            }
        }
        //----------------------
        $result = $wpdb->get_results("SELECT pageid,user_id FROM st_likepluginfbpagelist");
        if (count($result) > 0) {
            foreach ($result as $row) {
                $array = json_decode($this->get_facebook_wall($row->pageid));
                $data = array();
                $data['facebookpageid'] = $row->pageid;
                $data['numberofposts'] = $array->number_post;
                $data['numberofcomments'] = $array->number_comment;
                $data['numberoflikes'] = $array->number_like;
                $data['numberofshares'] = $array->number_share;
                $data['numberofusers'] = $array->number_user;
                $data['fancount'] = $array->fan_count;
                $data['user_id'] = $row->user_id;
                $time = mktime();
                $last = intval($time) - 24 * 3600;
                $day = date('d-m-Y', $last);
                $data['date'] = $day;
                $count = count($wpdb->get_results("SELECT * FROM st_likepluginfbpagestatistics WHERE date='" . $day . "' AND facebookpageid=" . $row->pageid));
                if ($count == 0) {
                    $wpdb->insert("st_likepluginfbpagestatistics", $data);
                }
            }
        }
        //--------
    }

    public function cronjob_sitemap() {
        global $wpdb;
        $result = $wpdb->get_results("SELECT * FROM st_sitemap");

        foreach ($result as $row) {
            $wpdb->query("DELETE FROM st_sitemap_link WHERE user_id=" . $row->user_id . " AND site_id =" . $row->id);
            if (substr($row->site_url, -4) == '.xml') {
                $xml = simplexml_load_file($row->site_url);
                $stt = 0;
                foreach ($xml as $name) {
                    $wpdb->insert('st_sitemap_link', array('link' => $name->loc, 'user_id' => $row->user_id, 'site_id' => $row->id));
                    $stt++;
                }
                $wpdb->update('st_sitemap', array('number' => $stt), array('id' => $row->id));
            } else {
                $link = file_get_contents($row->site_url);
                $array = explode("\n", $link);
                $stt = 0;
                foreach ($array as $name) {
                    if ($name != '') {
                        $wpdb->insert('st_sitemap_link', array('link' => $name, 'user_id' => $row->user_id, 'site_id' => $row->id));
                        $stt++;
                    }
                }
                $wpdb->update('st_sitemap', array('number' => $stt), array('id' => $row->id));
            }
        }
    }

    public function cronjob_search() {
        global $wpdb;
        $time = mktime();
        $last = intval($time) - 24 * 3600;
        $result = $wpdb->get_results("SELECT * FROM st_likepluginsearchterms");
        foreach ($result as $row) {
            $url = "http://graph.facebook.com/search?q=" . $row->searchterm . "&type=post&limit=1000&since=" . date('Y-m-d', $last) . "T" . urlencode(date('H:m:s')) . "%2B0000";
            $array = json_decode(file_get_contents($url));
            if (count($array) > 0) {
                foreach ($array as $value) {
                    foreach ($value as $value2) {
                        if ($value2->id != '') {
                            $data = array();
                            $data['messageid'] = $value2->id;
                            $data['searchtermid'] = $row->searchtermid;
                            $data['fromuserid'] = $value2->from->id;
                            $data['messagetypeid'] = $value2->type;
                            $data['messagetext'] = $value2->message;
                            $data['picture'] = $value2->picture;
                            $data['link'] = $value2->link;
                            $data['source'] = $value2->source;
                            $data['icon'] = $value2->icon;
                            $data['createdtime'] = $value2->created_time;
                            $data['updatedtime'] = $value2->updated_time;
                            $data['likes'] = $value2->likes;
                            $data['date'] = date('d-m-Y', $last);
                            $data['user_id'] = $row->user_id;
                            $type = array('%s', '%d', '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s', '%d');
                            $count = $wpdb->get_var("SELECT COUNT(*) FROM st_likepluginfbmessages WHERE messageid='" . $value2->id . "'");
                            if (intval($count) == 0) {
                                $wpdb->insert("st_likepluginfbmessages", $data, $type);
                            } else {
                                $wpdb->update("st_likepluginfbmessages", $data, array('messageid' => $value2->id), $type, array('%s'));
                            }
                            if ($value2->from->id != '') {
                                if (count($wpdb->get_results("SELECT * FROM st_likepluginfbusers WHERE uid=" . $value2->from->id)) == 0) {
                                    $user_info = array();
                                    $user = json_decode(file_get_contents("https://graph.facebook.com/" . $value2->from->id . "?fields=birthday,first_name,last_name,locale,gender"));
                                    $user_info['birthday'] = $user->birthday;
                                    $user_info['currentlocation'] = $user->current_location;
                                    $user_info['firstname'] = $user->first_name;
                                    $user_info['lastname'] = $user->last_name;
                                    $user_info['locale'] = $user->locale;
                                    $user_info['profileurl'] = $user->profile_url;
                                    $user_info['sex'] = $user->gender;
                                    $user_info['timezone'] = $user->timezone;
                                    $user_info['uid'] = $value2->from->id;
                                    $user_info['user_id'] = $row->user_id;
                                    $wpdb->insert("st_likepluginfbusers", $user_info);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    public function get_facebook_wall($pageid) {
        define('APP_API_KEY', $this->config['facebook_api_key']);
        define('APP_SECRET_KEY', $this->config['facebook_secret']);
        define('APP_ID', $this->config['facebook_app_id']);
        require_once $this->config['classDir'] . 'facebook/facebook.php';
        $facebook = new Facebook(APP_API_KEY, APP_SECRET_KEY, true);
        $pageId = $pageid;
        $infos = $facebook->api_client->stream_get(0, $pageId, null, null, 1000);
        $posts = $infos['posts'];
        $profiles = $infos['profiles'];
        $users = array();
        if (is_array($profiles)) {

            foreach ($profiles as $pr) {
                $users[$pr['id']] = $pr;
            }
        }
        $generalInformation1 = json_decode(file_get_contents("http://graph.facebook.com/{$pageId}"));
        $generalInformation = array();
        $generalInformation['number_post'] = 0;
        $generalInformation['number_comment'] = 0;
        $generalInformation['number_like'] = 0;
        $generalInformation['number_share'] = 0;
        $generalInformation['number_user'] = count($profiles);

        $hrefs = array();

        foreach ($generalInformation1 as $k => $v) {
            $generalInformation[$k] = $v;
        }
        //fan_count
        if (is_array($posts)) {
            foreach ($posts as $k => $post) {
                $generalInformation['number_post']++;
                $generalInformation['number_comment']+= $post['comments']['count'];
                $generalInformation['number_like']+= @ $post['likes']['count'];
                if (isset($post['attachment']['href'])) {
                    $hrefs[] = urlencode($post['attachment']['href']);
                }
            }
        }
        if (count($hrefs) > 0) {
            $hrefString = implode(",", $hrefs);
            $xml = simplexml_load_file('http://api.facebook.com/restserver.php?method=links.getStats&urls=' . $hrefString, NULL, LIBXML_NOBLANKS);
            foreach ($xml->link_stat as $item) {
                $generalInformation['number_share'] += $item->share_count;
            }
        }

        return json_encode($generalInformation);
    }

    public function registerView() {
        $views = array(
            'appPostcards' => 'default_theme',
            'display_facebook_pages' => 'default_theme',
            'facebook_wall_contact_form' => 'default_theme',
            'display_facebook_feeds' => 'default_theme',
            'cronjob_statistics' => 'default_theme',
            'cronjob_search' => 'default_theme',
            'image_map' => 'default_theme',
            'view_form' => 'default_theme'
        );
        $this->setView($views);
    }

    public function facebook_wall_contact_form() {
        echo 'hello world';
    }

    public function applications() {
        global $wpdb, $current_user;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Form Builder';
        $this->view->iconNew = 'Home';
        $this->view->iconAction = "loadPage('applications');";
        $this->view->wpdb = $wpdb;
        $this->view->result = $wpdb->get_results("SELECT * FROM st_ap_forms WHERE user_id = " . $current_user->ID);
        $this->view->default_id = $_POST['default_id'];
        $this->view->functions = $this->functions;
        $this->view->redirect = intval($_GET['redirect']);
    }

    public function gallery_app() {
        require_once $this->config['pluginDir'] . 'stPostcardsClassGallery.php';
        $stPostcardsClass = new stPostcardsClassGallery($this->config, $this->option);
        global $wpdb, $current_user;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Gallery';
        if (isset($_POST['id']) && isset($_POST['edit'])) {
            $result = $wpdb->get_results("SELECT * FROM st_ap_gallery WHERE user_id = " . $current_user->ID . " AND id = " . $_POST['id']);
            foreach ($result as $row) {
                $data['name'] = $row->name;
                $data['description'] = $row->description;
                $data['file_name'] = $row->file_name;
                $data['amazon_name'] = $row->amazon_name;
                $data['id'] = $_POST['id'];
            }
            $this->view->edit = json_encode($data);
            $this->view->album_id = $_POST['album_id'];
        }
        $this->view->model = $this->loadmodel("stFacebookGallery");
        if (isset($_POST['data'])) {
            $data['user_id'] = $current_user->ID;
            $data['file_name'] = $_POST['data']['upload_file'];
            $data['name'] = $_POST['data']['name'];
            $data['description'] = $_POST['data']['description'];
            if (intval($_POST['data']['id']) > 0) {
                $data['last_update'] = date('Y-m-d H:i:s');
                if ($_POST['data']['upload_file'] != $wpdb->get_var("SELECT file_name FROM st_ap_gallery WHERE id=" . $_POST['data']['id'])) {
                    $name = ('picture_' . $current_user->ID . '_' . $_POST['data']['id'] . '' . substr($_POST['data']['upload_file'], -4, 4));
                    $thumb_name = ('picture_' . $current_user->ID . '_' . $_POST['data']['id'] . '-thumb' . substr($_POST['data']['upload_file'], -4, 4));
                    $thumb_file = substr($_POST['data']['upload_file'], 0, strlen($_POST['data']['upload_file']) - 4) . '-thumb' . substr($_POST['data']['upload_file'], -4, 4);
                    $stPostcardsClass->deleteGallery('fb-app-gallery/' . $wpdb->get_var("SELECT amazon_name FROM st_ap_gallery WHERE user_id = " . $current_user->ID . " AND id = " . $_POST['data']['id']));
                    $stPostcardsClass->uploadGallery($_POST['data']['upload_file'], $name, $thumb_file, $thumb_name, 'fb-app-gallery/' . $current_user->user_login);
                    $data['amazon_name'] = $current_user->user_login . '/' . $name;
                    unlink($thumb_file);
                    unlink($_POST['data']['upload_file']);
                }
                $wpdb->update('st_ap_gallery', $data, array('id' => $_POST['data']['id']));

                $arg = array(
                    'status' => 'success',
                    //'title'    => 'Image uploaded',
                    'message' => __('Edit successful', $config['plugin_name'])
                );
                if (count($_POST['data']['album']) > 0) {
                    $picture_id = $_POST['data']['id'];
                    $wpdb->query("DELETE FROM st_gallery_album WHERE user_id = " . $current_user->ID . " AND picture_id = " . $picture_id);
                    foreach ($_POST['data']['album'] as $row) {
                        $wpdb->insert("st_gallery_album", array('user_id' => $current_user->ID, 'album_id' => $row, 'picture_id' => $picture_id));
                    }
                }
                echo $this->functions->sendMessage(json_encode($arg), 'gallery_app&album_id=' . $_POST['album_id'] . '&cur_page=' . $_POST['cur_page']);
                die;
            } else {
                $data['create_date'] = date('Y-m-d H:i:s');
                $data['last_update'] = date('Y-m-d H:i:s');
                $wpdb->insert('st_ap_gallery', $data);
                $max = $wpdb->get_var("SELECT MAX(id) FROM st_ap_gallery WHERE user_id=" . $current_user->ID);
                $name = ('picture_' . $current_user->ID . '_' . $max . '' . substr($_POST['data']['upload_file'], -4, 4));
                $thumb_name = ('picture_' . $current_user->ID . '_' . $max . '-thumb' . substr($_POST['data']['upload_file'], -4, 4));
                $thumb_file = substr($_POST['data']['upload_file'], 0, strlen($_POST['data']['upload_file']) - 4) . '-thumb' . substr($_POST['data']['upload_file'], -4, 4);
                $stPostcardsClass->uploadGallery($_POST['data']['upload_file'], $name, $thumb_file, $thumb_name, 'fb-app-gallery/' . $current_user->user_login);
                $data['amazon_name'] = $current_user->user_login . '/' . $name;
                $wpdb->update('st_ap_gallery', $data, array('id' => $max));
                if (count($_POST['data']['album']) > 0) {
                    $picture_id = $wpdb->get_var("SELECT MAX(id) FROM st_ap_gallery WHERE user_id=" . $current_user->ID);
                    foreach ($_POST['data']['album'] as $row) {
                        $wpdb->insert("st_gallery_album", array('user_id' => $current_user->ID, 'album_id' => $row, 'picture_id' => $picture_id));
                    }
                }
                unlink($_POST['data']['upload_file']);
                unlink($thumb_file);
                $arg = array(
                    'status' => 'success',
                    'title' => 'Image uploaded',
                    'message' => __('New image successfully uploaded', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg), 'gallery_app&album_id=' . $_POST['album_id'] . '&cur_page=' . $_POST['cur_page']);
                die;
            }
        }
        $stFacebookToolbox_model = $this->loadmodel("stFacebookGallery");
        // short action handle
        if ($_REQUEST['short_action'] == 'delete') {
            $image = $wpdb->get_var("SELECT amazon_name FROM st_ap_gallery WHERE id = " . $_POST['id']);
            $stPostcardsClass->deleteGallery($image);
            $wpdb->query("DELETE FROM st_ap_gallery WHERE id = " . $_POST['id'] . " AND user_id = " . $current_user->ID);
            $arg = array(
                'status' => 'success',
                'message' => __('Delete successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));
        }

        $args = array();
        if (intval($_POST['album_id']) != 0) {
            $where = $wpdb->get_results("SELECT picture_id FROM st_gallery_album WHERE album_id = " . $_POST['album_id'] . " AND user_id = " . $current_user->ID);
            $data = array();
            foreach ($where as $wh) {
                $data[] = $wh->picture_id;
            }
            $where = ' AND id IN (' . implode(',', $data) . ')';
        } else {
            $where = '';
        }
        $args['where'] = ' user_id = ' . $current_user->ID . $where;
        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;

        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 'id';
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 'DESC';
        if ($_REQUEST['sort']) {
            $args['order'] = array($sort, $sort_type);
        }
        $args['limit'] = array($start, $limit);

        $results = $stFacebookToolbox_model->getRecords($args);
        $total = $wpdb->get_var("SELECT COUNT(*) FROM st_ap_gallery WHERE user_id = " . $current_user->ID . $where);
        $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName);

        $columns = array(
            'id' => __('ID', $this->config['plugin_name']),
            'name' => __('Name', $this->config['plugin_name']),
            'picture_name' => __('Picture', $this->config['plugin_name']),
            'description' => __('Description', $this->config['plugin_name']),
            'last_update' => __('Last Update', $this->config['plugin_name']),
        );
        register_column_headers('stFacebookToolbox_stFacebookToolbox', $columns);

        //initialize variable to view
        $this->view->results = $results;
        $this->view->pagination = $pagination;
        $this->view->album = $wpdb->get_results("SELECT * FROM st_ap_album WHERE user_id = " . $current_user->ID);
        $this->view->album_id = $_POST['album_id'];
        $this->view->cur_page = $cur_page;
    }
    
    public function coupon_facebook_setting(){
        die;
         global $wpdb,$current_user;
         $this->view->headIcon = 'icon_re';
         $this->view->headTitle1 = 'Facebook Settings';
         if(isset($_POST['data'])){
             $data['app_id'] = $_POST['data']['app_id'];
             $data['secrect'] = $_POST['data']['secrect'];
             $data['user_id'] = $current_user->ID;
             if($wpdb->get_var("SELECT COUNT(*) FROM st_coupons_facebook_setting WHERE user_id = $current_user->ID") > 0){
                 $wpdb->update('st_coupons_facebook_setting',$data,array('user_id'=>$current_user->ID));
             }
             else {
                 $wpdb->insert('st_coupons_facebook_setting',$data);
             }
             $arg = array(
                'status' => 'success',
                'message' => __('Setting saved successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg),'coupon_facebook_setting');
         }
         $this->view->result = $wpdb->get_row("SELECT * FROM st_coupons_facebook_setting WHERE user_id = $current_user->ID");
    }
    
    public function coupon_user_referer(){
         global $wpdb,$current_user;
         $stFacebookToolbox_model = $this->loadmodel("stFacebookCouponUser");
        $args = array();
        if ($_REQUEST['short_action'] == 'delete') {
           $wpdb->query("DELETE FROM st_coupon_users WHERE CouponUserID = " . $_POST['id']);
           $wpdb->query("DELETE FROM st_coupon_referer WHERE customerID  = " . $_POST['id']);
            $arg = array(
                'status' => 'success',
                'message' => __('Delete successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));
        }
        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;
        //$args['where'] = ' user_id = '.$current_user->ID;
        $args['where'] = ' user_id = '.$current_user->ID.' AND CouponUserID IN (SELECT customerID FROM st_coupon_referer WHERE RefererID = '.$_POST['referer'].') ';
        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 0;
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 0;
        if ($_REQUEST['sort']) {
            $args['order'] = array($sort, $sort_type);
        }
        $args['limit'] = array($start, $limit);

        $results = $stFacebookToolbox_model->getRecords($args);
        $total = $wpdb->get_var("SELECT COUNT(*) FROM st_coupon_users WHERE {$args['where']}");
        $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName);

        $columns = array(
            'Name' => __('Name', $this->config['plugin_name']),
            'Gender' => __('Gender', $this->config['plugin_name']),
            'email' => __('Email', $this->config['plugin_name']),
            'BirthDate' => __('Birth Date', $this->config['plugin_name']),
            'HomeTown'=> __('Location', $this->config['plugin_name']),
            'user_id'=> __('Referred', $this->config['plugin_name']),
            
        );
        register_column_headers('stFacebookToolbox_stFacebookToolbox', $columns);

        //initialize variable to view
        $this->view->results = $results;
        $this->view->pagination = $pagination;
        $this->view->campaign = $wpdb->get_results("SELECT * FROM st_coupon_templates WHERE user_id = ".$current_user->ID);
        $this->view->all_user = $wpdb->get_var("SELECT COUNT(*) FROM st_coupon_users WHERE user_id = $current_user->ID");
        $this->view->model = $stFacebookToolbox_model;
        $this->view->default_campaign = $_POST['default_campaign'];
        
    
    }
    public function coupon_user(){
        global $wpdb,$current_user;
        $this->view->user = $current_user->ID;
        $stFacebookToolbox_model = $this->loadmodel("stFacebookCouponUser");
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'User / Customer';
        $args = array();
        if ($_REQUEST['short_action'] == 'delete') {
           if($wpdb->get_var("SELECT COUNT(*) FROM st_coupon_user_to_user WHERE coupon_user_id = ".$_POST['id']) <= 1){
                $wpdb->query("DELETE FROM st_coupon_users WHERE CouponUserID = " . $_POST['id']);
                $wpdb->query("DELETE FROM st_coupon_referer WHERE customerID  = " . $_POST['id']);
                $wpdb->query("DELETE FROM st_coupon_user_to_user WHERE coupon_user_id = ".$_POST['id']." AND user_id = ".$current_user->ID);
            }
            else {
                $wpdb->query("DELETE FROM st_coupon_user_to_user WHERE coupon_user_id = ".$_POST['id']." AND user_id = ".$current_user->ID);
            }
            $arg = array(
                'status' => 'success',
                'message' => __('Delete successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));
        }
        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;
        //$args['where'] = ' user_id = '.$current_user->ID;
        if(intval($_POST['default_campaign']) > 0)
            $args['where'] = ' CouponUserID IN (SELECT CouponUserID FROM st_coupons WHERE CouponTemplateID = '.$_POST['default_campaign'].') ';
        else
            $args['where'] = ' CouponUserID IN (SELECT coupon_user_id FROM st_coupon_user_to_user WHERE user_id = '.$current_user->ID.')';
        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 0;
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 0;
        if ($_REQUEST['sort']) {
            $args['order'] = array($sort, $sort_type);
        }
        $args['limit'] = array($start, $limit);

        $results = $stFacebookToolbox_model->getRecords($args);
        $total = $wpdb->get_var("SELECT COUNT(*) FROM st_coupon_users WHERE {$args['where']}");
        $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName);

        $columns = array(
            'Name' => __('Name', $this->config['plugin_name']),
            'Gender' => __('Gender', $this->config['plugin_name']),
            'email' => __('Email', $this->config['plugin_name']),
            'BirthDate' => __('Birth Date', $this->config['plugin_name']),
            'HomeTown'=> __('Location', $this->config['plugin_name']),
            'user_id'=> __('Referred', $this->config['plugin_name']),
            
        );
        register_column_headers('stFacebookToolbox_stFacebookToolbox', $columns);

        //initialize variable to view
        $this->view->results = $results;
        $this->view->pagination = $pagination;
        $this->view->campaign = $wpdb->get_results("SELECT * FROM st_coupon_templates WHERE user_id = ".$current_user->ID." ORDER BY CouponTemplateName ASC");
        $this->view->all_user = $wpdb->get_var("SELECT COUNT(*) FROM st_coupon_users WHERE user_id = $current_user->ID");
        $this->view->model = $stFacebookToolbox_model;
        $this->view->default_campaign = $_POST['default_campaign'];
        
    }
    
    public function coupon_user_statistics(){
        global $wpdb,$current_user;
        $stFacebookToolbox_model = $this->loadmodel("stFacebookCouponUser");
        $this->view->user = $current_user->ID;
        $args = array();
        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;
       $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 0;
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 0;
        if ($_REQUEST['sort']) {
            $args['order'] = array($sort, $sort_type);
        }
        $args['where'] = ' CouponUserID IN (SELECT CouponUserID FROM st_coupons WHERE CouponTemplateID = '.$_POST['template_id'].')';
        $args['limit'] = array($start, $limit);

        $results = $stFacebookToolbox_model->getRecords($args);
        $total = $wpdb->get_var("SELECT COUNT(*) FROM st_coupon_users WHERE {$args['where']}");
        $pagination = $this->functions->pagination2($start, $limit, $total, $cur_page, $this->actionName.'&template_id='.$_POST['template_id']);

        $columns = array(
            'CouponUserID' => __('ID', $this->config['plugin_name']),
            'Name' => __('Customer Name', $this->config['plugin_name']),
            'HomeTown' => __('Campaign', $this->config['plugin_name']),
            'BirthDate' => __('Generated Date', $this->config['plugin_name']),
            'Gender'=> __('Sale', $this->config['plugin_name']),
            
        );
        register_column_headers('stFacebookToolbox_stFacebookToolbox', $columns);

        //initialize variable to view
        $this->view->results = $results;
        $this->view->pagination = $pagination;
        $this->view->model = $stFacebookToolbox_model;
        $this->view->template_id = $_POST['template_id'];
        $this->view->campain = $wpdb->get_var("SELECT CouponTemplateName FROM st_coupon_templates WHERE CouponTemplateID = ".$_POST['template_id']);
    }
    
    public function coupon_user_report(){
        global $wpdb,$current_user;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Customers Report';
        $this->view->campaign = $wpdb->get_results("SELECT * FROM st_coupon_templates WHERE user_id = ".$current_user->ID." ORDER BY CouponTemplateName ASC");
        $this->view->user = $current_user->ID;
    }
    public function coupon_sales_report(){
        global $wpdb,$current_user;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Sales Report';
        $this->view->campaign = $wpdb->get_results("SELECT * FROM st_coupon_templates WHERE user_id = ".$current_user->ID." ORDER BY CouponTemplateName ASC");
        $this->view->user = $current_user->ID;
    }
    public function coupon_report(){
        global $wpdb,$current_user;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Coupon Report';
        $this->view->campaign = $wpdb->get_results("SELECT * FROM st_coupon_templates WHERE user_id = ".$current_user->ID." ORDER BY CouponTemplateName ASC");
        $this->view->user = $current_user->ID;
    }
    public function coupon_campaigns_report(){
        global $wpdb,$current_user;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Campaigns Report';
        $this->view->user = $current_user->ID;
    }
    
    public function coupon_statistics(){
        global $wpdb,$current_user;
        $stFacebookToolbox_model = $this->loadmodel("stFacebookCouponStatistics");
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Statistics';
        $this->view->number_coupon = $wpdb->get_var("SELECT COUNT(*) FROM st_coupons WHERE user_id = $current_user->ID");
        $this->view->number_sales  = $wpdb->get_var("SELECT COUNT(*) FROM st_coupon_sales WHERE user_id = $current_user->ID");
        $this->view->referer_coupon = $wpdb->get_var("SELECT COUNT(*) FROM st_coupons WHERE user_id = $current_user->ID AND CouponUserID IN (SELECT customerID FROM st_coupon_referer WHERE user_id = $current_user->ID )");
        $args = array();
        $args['where'] = ' user_id = ' . $current_user->ID;
        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;

        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 0;
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 0;
        if ($_REQUEST['sort']) {
            $args['order'] = array($sort, $sort_type);
        }
        $args['limit'] = array($start, $limit);

        $results = $stFacebookToolbox_model->getRecords($args);
        $total = $stFacebookToolbox_model->countRecords();
        $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName);

        $columns = array(
            'CouponTemplateID' => __('ID', $this->config['plugin_name']),
            'CouponTemplateName' => __('Campaign', $this->config['plugin_name']),
            'DiscountTypeID ' => __('No. of coupon generated', $this->config['plugin_name']),
            'ValidFromDateTime'=> __('No. of sales', $this->config['plugin_name']),
        );
        register_column_headers('stFacebookToolbox_stFacebookToolbox', $columns);

        //initialize variable to view
        $this->view->results = $results;
        $this->view->pagination = $pagination;
        $this->view->model = $stFacebookToolbox_model;
                
    }
    
    public function coupon(){
        global $wpdb,$current_user;
        $stFacebookToolbox_model = $this->loadmodel("stFacebookCoupon");
        
        $this->view->headIcon = 'icon_re';
        if(!isset($_POST['user_id'])){
        $this->view->headTitle1 = 'Coupons';
        }
        else {
           $this->view->headTitle1 = ''; 
        }
        $this->view->user_id = $_POST['user_id'];
        $args = array();
         require_once $this->config['pluginDir'] . 'stPostcardsClassGallery.php';
        $stPostcardsClass = new stPostcardsClassGallery($this->config, $this->option);
        if ($_REQUEST['short_action'] == 'delete') {
           $image = $wpdb->get_var("SELECT QCCodePath FROM st_coupons WHERE CouponID = ".$_POST['id']);
           $template = $wpdb->get_var("SELECT CouponTemplateID FROM st_coupons WHERE CouponID = ".$_POST['id']);
           $pdf = $wpdb->get_var("SELECT CouponCode FROM st_coupons WHERE CouponID = ".$_POST['id']).'-'.$wpdb->get_var("SELECT SequenceNumber FROM st_coupon_templates WHERE CouponTemplateID = (SELECT CouponTemplateID FROM st_coupons WHERE CouponID = ".$_POST['id'].")").'.pdf';
           $array_image = explode('/',$image);
           $image = $array_image[count($array_image)-1];
           $stPostcardsClass->deleteGallery('fb-app-coupon/qr/'.$image);
            $stPostcardsClass->deleteGallery('fb-app-coupon/pdf/'.$pdf);
           $wpdb->query("DELETE FROM st_coupons WHERE CouponID 	 = " . $_POST['id']);
           $available_number_of_coupons = $wpdb->get_var("SELECT available_number_of_coupons FROM st_coupon_templates WHERE CouponTemplateID = ".$template);
           $wpdb->update('st_coupon_templates',array('available_number_of_coupons'=>intval($available_number_of_coupons+1)),array('CouponTemplateID'=>$template));
            $arg = array(
                'status' => 'success',
                'message' => __('Delete successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));
        }
        $args['where'] = ' user_id = '.$current_user->ID;
        if(isset($_POST['user_id'])){
            $args['where'] .= ' AND CouponUserID = '.$_POST['user_id'];
        }
        elseif(isset($_POST['campaign'])){
            if($_POST['campaign'] != 'all')
                $args['where'] .= ' AND CouponTemplateID = '.$_POST['campaign'];
        }
        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;

        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 0;
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 0;
        if ($_REQUEST['sort']) {
            $args['order'] = array($sort, $sort_type);
        }
        else {
             $args['order'] = array('CouponID', 'DESC');
        } // sort
        $args['limit'] = array($start, $limit);

        $results = $stFacebookToolbox_model->getRecords($args);
        $total = $wpdb->get_var("SELECT COUNT(*) FROM st_coupons WHERE {$args['where']}");
        $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName);

        $columns = array(
            'CouponUserID' => __('Customer', $this->config['plugin_name']),
            'CouponGeneratedDateTime' => __('Coupon Generated', $this->config['plugin_name']),
            'CouponTemplateID' => __('Campaign', $this->config['plugin_name']),
            'QCCodePath' => __('QC Code', $this->config['plugin_name']),
            'GeneratedCouponPath'=> __('Coupon', $this->config['plugin_name']),
            
        );
        register_column_headers('stFacebookToolbox_stFacebookToolbox', $columns);

        //initialize variable to view
        $this->view->results = $results;
        $this->view->pagination = $pagination;
        $this->view->model = $stFacebookToolbox_model;
        $this->view->campaign = $wpdb->get_results("SELECT * FROM st_coupon_templates WHERE user_id = ".$current_user->ID." ORDER BY CouponTemplateName ASC");
        $this->view->campaign_select = $_POST['campaign'];
        $this->view->action = $_GET['action'];
        $this->view->check = $_POST['check'];
        $this->view->cur_page = $cur_page;
    }
    
    public function coupon_template(){
        global $wpdb,$current_user;
         if ($_REQUEST['short_action'] == 'delete') {
            $wpdb->query("DELETE FROM st_coupon_templates WHERE CouponTemplateID = " . $_POST['id'] . " AND user_id = " . $current_user->ID);
            $arg = array(
                'status' => 'success',
                'message' => __('Delete successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));
        }
        if(isset($_POST['active'])){
            $wpdb->update('st_coupon_templates',array('status'=>0,'user_id'=>$current_user->ID),array('status'=>1,'user_id'=>$current_user->ID));
            $wpdb->update('st_coupon_templates',array('status'=>1,'user_id'=>$current_user->ID),array('CouponTemplateID'=>$_POST['active'],'user_id'=>$current_user->ID));
            $arg = array(
                'status' => 'success',
                'message' => __('Campain Activated', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));
        }
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Campaigns';
        $this->view->iconNew = 'Add New Campaign';
        $this->view->iconAction = "redirect('".get_bloginfo('url')."/wp-admin/admin.php?page=stFacebookToolbox&action=add_coupon_template');";
        $stFacebookToolbox_model = $this->loadmodel("stFacebookCouponTemplate");
        $args = array();
        $args['where'] = ' user_id = ' . $current_user->ID;
        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;

        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 0;
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 0;
        if ($_REQUEST['sort']) {
            $args['order'] = array($sort, $sort_type);
        }
        $args['limit'] = array($start, $limit);

        $results = $stFacebookToolbox_model->getRecords($args);
        $total = $wpdb->get_var("SELECT COUNT(*) FROM st_coupon_templates WHERE user_id = $current_user->ID ");
        $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName);

        $columns = array(
            'CouponTemplateID' => __('ID', $this->config['plugin_name']),
            'CouponTemplateName' => __('Campaign', $this->config['plugin_name']),
            'CouponTemplateGraphicsID' => __('Graphics', $this->config['plugin_name']),
            'ValidFromDateTime'=> __('Valid From', $this->config['plugin_name']),
            'ValidToDateTime'=> __('Valid To', $this->config['plugin_name']),
            'DiscountTypeID'=> __('Discount Type', $this->config['plugin_name']),
            'DiscountValue'=> __('Discount Value', $this->config['plugin_name']),
        );
        register_column_headers('stFacebookToolbox_stFacebookToolbox', $columns);

        //initialize variable to view
        $this->view->results = $results;
        $this->view->pagination = $pagination;
        $this->view->model = $stFacebookToolbox_model;
        $this->view->active = $wpdb->get_var("SELECT CouponTemplateName FROM st_coupon_templates WHERE status = 1 AND user_id = $current_user->ID");
        $this->view->user_id = $current_user->ID;
        
    }
    
    
    
    public function edit_coupon_template(){
        $path = str_replace('wp-content/plugins/stSocialMediaToolbox/Toolboxes/stFacebookToolbox/','',$this->config ['pluginDir']);
        $this->view->headIcon = 'icon_re';
        global $wpdb,$current_user;
        if(isset($_POST['data'])){
            $from = explode('.',substr($_POST['data']['from'],0,10));
            $from = $from[2].'-'.$from[1].'-'.$from[0].' '.substr($_POST['data']['from'],11).':00';
            $to = explode('.',substr($_POST['data']['to'],0,10));
            $to = $to[2].'-'.$to[1].'-'.$to[0].' '.substr($_POST['data']['to'],11).':00';
            $is_fan = (isset($_POST['data']['is_fan']))?1:0;
            $is_share = (isset($_POST['data']['is_share']))?1:0;
            $auto_post = (isset($_POST['data']['auto_post']))?1:0;
            $data['auto_post'] = $auto_post;
            $data['wall_title'] = strip_tags($_POST['data']['wall_title']);
            $data['wall_text'] = strip_tags($_POST['data']['wall_text']);
            $data['wall_image'] = $_POST['data']['upload_file'];
            $data['image_before'] = $_POST['data']['upload_button'];
            //$data['term_and_condition'] = $_POST['data']['term_and_condition'];
            $data['CouponTemplateName'] = $_POST['data']['name'];
            $data['CouponTemplateDescription'] = $_POST['data']['description'];
            $data['CouponTemplateGraphicsID'] = $_POST['data']['graphic'];
            $data['ValidFromDateTime'] = $from;
            $data['ValidToDateTime'] = $to;
            $data['campaign_type'] = $_POST['data']['campaign_type'];
            $data['url'] = $_POST['data']['url'];
            $data['coupon_limit'] = $_POST['data']['coupon_limit'];
            $data['CouponTitle'] = $_POST['data']['title'];
            $data['coupon_detail'] = $_POST['data']['editor_content'];
            $data['DiscountTypeID'] = $_POST['data']['type'];
            $data['DiscountValue'] = $_POST['data']['value'];
            $data['available_number_of_coupons'] = ($_POST['data']['coupon_limit'] - $wpdb->get_var("SELECT COUNT(*) FROM st_coupons WHERE CouponTemplateID = {$_POST['data']['id']}"));
            $data['is_fan'] = $is_fan;
            $data['is_share'] = $is_share;
            $data['CouponSecondTitle'] = $_POST['data']['second'];
            $data['user_id'] = $current_user->ID;
            $wpdb->update('st_coupon_templates',$data,array('CouponTemplateID'=>$_POST['data']['id']));
            $arg = array(
                    'status' => 'success',
                    //'title' => 'Ad',
                    'message' => __('Edited successfully', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg), 'coupon_template');
                die;
        }
       $this->view->result = $result =  $wpdb->get_results("SELECT * FROM st_coupon_templates WHERE CouponTemplateID = ".$_GET['id']);
        $this->view->headTitle1 = 'Edit Campaign "'.$result[0]->CouponTemplateName.'"';
        $this->view->iconNew = 'Preview';
        $this->view->iconAction = "return_false();";
        $this->view->number_coupon = $wpdb->get_var("SELECT COUNT(*) FROM st_coupons WHERE CouponTemplateID = {$_GET['id']}");
        $this->view->graphic = $wpdb->get_results("SELECT * FROM st_coupon_template_graphics WHERE user_id = ".$current_user->ID);
        $this->view->type = $wpdb->get_results("SELECT * FROM st_discount_types WHERE user_id = ".$current_user->ID);
        do_action("admin_print_styles-post-php");
        do_action('admin_print_styles');
        remove_all_filters('mce_external_plugins');
        $this->view->action = $_GET['action'];
    }
    
    public function add_coupon_template(){

        global $wpdb,$current_user;
        if(isset($_POST['data'])){
            $from = explode('.',substr($_POST['data']['from'],0,10));
            $from = $from[2].'-'.$from[1].'-'.$from[0].' '.substr($_POST['data']['from'],11).':00';
            $to = explode('.',substr($_POST['data']['to'],0,10));
            $to = $to[2].'-'.$to[1].'-'.$to[0].' '.substr($_POST['data']['to'],11).':00';
            $random = $this->getRandomString();
            while($wpdb->get_var("SELECT COUNT(*) FROM st_coupon_templates WHERE SequenceNumber = '".$random."'") > 0){
                $random = $this->getRandomString();
            }
            $is_fan = (isset($_POST['data']['is_fan']))?1:0;
            $is_share = (isset($_POST['data']['is_share']))?1:0;
            
            $data['CouponTemplateName'] = strip_tags($_POST['data']['name']);
            $data['is_fan'] = $is_fan;
            $data['is_share'] = $is_share;
            $auto_post = (isset($_POST['data']['auto_post']))?1:0;
            $data['auto_post'] = $auto_post;
            $data['wall_title'] = strip_tags($_POST['data']['wall_title']);
            $data['wall_text'] = strip_tags($_POST['data']['wall_text']);
            $data['wall_image'] = $_POST['data']['upload_file'];
            $data['image_before'] = $_POST['data']['upload_button'];
            $data['CouponTemplateDescription'] = $_POST['data']['description'];
            $data['CouponTemplateGraphicsID'] = $_POST['data']['graphic'];
            $data['ValidFromDateTime'] = $from;
            $data['ValidToDateTime'] = $to;
            $data['DiscountTypeID'] = $_POST['data']['type'];
            $data['DiscountValue'] = $_POST['data']['value'];
            $data['CouponTitle'] = $_POST['data']['title'];
            $data['SequenceNumber'] = $random;
            $data['coupon_limit'] = $_POST['data']['coupon_limit'];
            $data['CouponSecondTitle'] = $_POST['data']['second'];
            $data['coupon_detail'] = $_POST['data']['editor_content'];
            $data['available_number_of_coupons'] = $_POST['data']['coupon_limit'];
            $data['user_id'] = $current_user->ID;
            $data['campaign_type'] = $_POST['data']['campaign_type'];
            $data['url'] = $_POST['data']['url'];
            //$data['term_and_condition'] = $_POST['data']['term_and_condition'];
            $wpdb->insert('st_coupon_templates',$data);
            $arg = array(
                    'status' => 'success',
                    //'title' => 'Ad',
                    'message' => __('Added successfully', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg), 'coupon_template');
                die;
        }
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Add new Campaign';
        $this->view->graphic = $wpdb->get_results("SELECT * FROM st_coupon_template_graphics WHERE user_id = ".$current_user->ID);
        do_action("admin_print_styles-post-php");
        do_action('admin_print_styles');
        remove_all_filters('mce_external_plugins');
        $this->view->type = $wpdb->get_results("SELECT * FROM st_discount_types WHERE user_id = ".$current_user->ID);
        $this->view->action = $_GET['action'];

    }
    
    public function coupon_template_graphic(){
        die;
        $path = str_replace('wp-content/plugins/stSocialMediaToolbox/Toolboxes/stFacebookToolbox/','',$this->config ['pluginDir']);
        $this->view->graphic_config = include $path.'coupon/config/graphicConfig.php';
        global $wpdb,$current_user;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Coupon template graphics';
         require_once $this->config['pluginDir'] . 'stPostcardsClassGallery.php';
        $stPostcardsClass = new stPostcardsClassGallery($this->config, $this->option);
         $stFacebookToolbox_model = $this->loadmodel("stFacebookCouponGraphic");
         if(isset($_POST['id']) && $_POST['edit'] == '1'){
             $result = $wpdb->get_results("SELECT * FROM st_coupon_template_graphics WHERE user_id = " . $current_user->ID . " AND CouponTemplateGraphicsID = " . $_POST['id']);
            foreach ($result as $row) {
                $data['TemplatesGraphicsName'] = $row->TemplatesGraphicsName;
                $data['TemplatesGraphicsPath'] = $row->TemplatesGraphicsPath;
                $data['TemplatesPDFPath'] = $row->TemplatesPDFPath;
                $data['graphicConfig'] = $row->graphicConfig;
                $data['CouponTemplateGraphicsID'] = $_POST['id'];
            }
            $this->view->edit = json_encode($data);
         }
         if(isset($_POST['data'])){
             if($_POST['data']['id'] == ''){
                $data['TemplatesGraphicsName'] = $_POST['data']['name'];
                $data['user_id'] = $current_user->ID;
                $data['graphicConfig'] = $_POST['data']['config'];
                $wpdb->insert('st_coupon_template_graphics',$data);
                $max =  $wpdb->get_var("SELECT MAX(CouponTemplateGraphicsID) FROM st_coupon_template_graphics WHERE user_id = ".$current_user->ID);
                $name = ('template_' . $current_user->ID . '_' . $max . '' . substr($_POST['data']['upload_file'], -4, 4));
                $pdf_name = 'pdf_'.$current_user->ID.'_'.$max.substr($_POST['data']['upload_pdf'], -4, 4);
                $thumb_name = ('template_' . $current_user->ID . '_' . $max . '-thumb' . substr($_POST['data']['upload_file'], -4, 4));
                $thumb_file = substr($_POST['data']['upload_file'], 0, strlen($_POST['data']['upload_file']) - 4) . '-thumb' . substr($_POST['data']['upload_file'], -4, 4);
                $stPostcardsClass->uploadGallery($_POST['data']['upload_file'], $name, $thumb_file, $thumb_name, 'fb-app-coupon/' . $current_user->ID);
                $stPostcardsClass->uploadGallery($_POST['data']['upload_pdf'], $pdf_name, '', '', 'fb-app-coupon/' . $current_user->ID);
                $data['TemplatesGraphicsPath'] = $current_user->ID . '/' . $name;
                $data['TemplatesPDFPath'] = $current_user->ID. '/'.$pdf_name;
                $wpdb->update('st_coupon_template_graphics',$data,array('CouponTemplateGraphicsID'=>$max));
                unlink($_POST['data']['upload_file']);
                unlink($thumb_file);
                unlink($_POST['data']['upload_pdf']);
                $arg = array(
                    'status' => 'success',
                    'title' => 'Template uploaded',
                    'message' => __('New Template successfully uploaded', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg),'coupon_template_graphic');
                die;
             }
             elseif(intval($_POST['data']['edit']) == 1) {
                    if ($_POST['data']['upload_file'] != $wpdb->get_var("SELECT TemplatesGraphicsPath FROM st_coupon_template_graphics WHERE CouponTemplateGraphicsID=" . $_POST['data']['id'])) {
                    $name = ('template_' . $current_user->ID . '_' . $_POST['data']['id'] . '' . substr($_POST['data']['upload_file'], -4, 4));
                    $thumb_name = ('template_' . $current_user->ID . '_' . $_POST['data']['id'] . '-thumb' . substr($_POST['data']['upload_file'], -4, 4));
                    $thumb_file = substr($_POST['data']['upload_file'], 0, strlen($_POST['data']['upload_file']) - 4) . '-thumb' . substr($_POST['data']['upload_file'], -4, 4);
                    $stPostcardsClass->deleteGallery('fb-app-coupon/' . $wpdb->get_var("SELECT TemplatesGraphicsPath FROM st_coupon_template_graphics WHERE CouponTemplateGraphicsID=" . $_POST['data']['id']));
                    $stPostcardsClass->uploadGallery($_POST['data']['upload_file'], $name, $thumb_file, $thumb_name, 'fb-app-coupon/' . $current_user->ID);
                    $data['TemplatesGraphicsPath'] = $current_user->ID . '/' . $name;
                    unlink($thumb_file);
                    unlink($_POST['data']['upload_file']);
                    
                    
                }
                if ($_POST['data']['upload_pdf'] != $wpdb->get_var("SELECT TemplatesPDFPath FROM st_coupon_template_graphics WHERE CouponTemplateGraphicsID=" . $_POST['data']['id'])) {
                    $name = ('pdf_' . $current_user->ID . '_' . $_POST['data']['id'] . '' . substr($_POST['data']['upload_pdf'], -4, 4));
                    $stPostcardsClass->deleteGallery('fb-app-coupon/' . $wpdb->get_var("SELECT TemplatesPDFPath FROM st_coupon_template_graphics WHERE CouponTemplateGraphicsID=" . $_POST['data']['id']));
                    $stPostcardsClass->uploadGallery($_POST['data']['upload_pdf'], $name, '', '', 'fb-app-coupon/' . $current_user->ID);
                    $data['TemplatesPDFPath'] = $current_user->ID . '/' . $name;
                    unlink($_POST['data']['upload_pdf']);
                    
                    
                }
                $data['TemplatesGraphicsName'] = $_POST['data']['name'];
                $data['user_id'] = $current_user->ID;
                $data['graphicConfig'] = $_POST['data']['config'];
                $wpdb->update('st_coupon_template_graphics', $data, array('CouponTemplateGraphicsID' => $_POST['data']['id']));

                    $arg = array(
                        'status' => 'success',
                        //'title'    => 'Image uploaded',
                        'message' => __('Edit successful', $config['plugin_name'])
                    );
                    echo $this->functions->sendMessage(json_encode($arg),'coupon_template_graphic');
             }
         }
        // short action handle
        if ($_REQUEST['short_action'] == 'delete') {
            $image = $wpdb->get_var("SELECT TemplatesGraphicsPath FROM st_coupon_template_graphics WHERE CouponTemplateGraphicsID = " . $_POST['id']);
            $pdf = $wpdb->get_var("SELECT TemplatesPDFPath FROM st_coupon_template_graphics WHERE CouponTemplateGraphicsID = " . $_POST['id']);
            $stPostcardsClass->deleteGallery($image);
             $stPostcardsClass->deleteGallery($pdf);
            $wpdb->query("DELETE FROM st_coupon_template_graphics WHERE CouponTemplateGraphicsID = " . $_POST['id'] . " AND user_id = " . $current_user->ID);
            $arg = array(
                'status' => 'success',
                'message' => __('Delete successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));
        }

        $args = array();
        $args['where'] = ' user_id = ' . $current_user->ID;
        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;

        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 'id';
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 'DESC';
        if ($_REQUEST['sort']) {
            $args['order'] = array($sort, $sort_type);
        }
        $args['limit'] = array($start, $limit);

        $results = $stFacebookToolbox_model->getRecords($args);
        $total = $wpdb->get_var("SELECT COUNT(*) FROM st_coupon_template_graphics WHERE user_id = " . $current_user->ID);
        $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName);

        $columns = array(
            'CouponTemplateGraphicsID' => __('ID', $this->config['plugin_name']),
            'TemplatesGraphicsName' => __('Name', $this->config['plugin_name']),
            'TemplatesGraphicsPath' => __('Picture', $this->config['plugin_name']),
          );
        register_column_headers('stFacebookToolbox_stFacebookToolbox', $columns);

        //initialize variable to view
        $this->view->results = $results;
        $this->view->pagination = $pagination;
    }

    public function coupon_discount_type(){
        global $wpdb,$current_user;
         if ($_REQUEST['short_action'] == 'delete') {
            $wpdb->query("DELETE FROM st_discount_types WHERE DiscountTypeID = " . $_POST['id'] . " AND user_id = " . $current_user->ID);
            $arg = array(
                'status' => 'success',
                'message' => __('Delete successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));
        }
        if(isset($_POST['data'])){
            $data['DiscountTypeName'] = $_POST['data']['name'];
            $data['DiscountTypeCalculation'] = $_POST['data']['calculation'];
            $data['user_id'] = $current_user->ID;
            if($_POST['data']['id'] == ''){
                $wpdb->insert('st_discount_types',$data);
                $arg = array(
                    'status' => 'success',
                    'title' => 'Discount added',
                    'message' => __('New Discount Type successfully added', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg),'coupon_discount_type');
                die;
            }else {
                $wpdb->update('st_discount_types',$data,array('DiscountTypeID'=>$_POST['data']['id']));
                $arg = array(
                    'status' => 'success',
                    //'title' => 'Discount added',
                    'message' => __('Edit successfully', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg),'coupon_discount_type');
                die;
            }
        }
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Coupon Discount Types';
        $stFacebookToolbox_model = $this->loadmodel("stFacebookDiscountTypes");
        $args = array();
        $args['where'] = ' user_id = ' . $current_user->ID;
        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;

        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 0;
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 0;
        if ($_REQUEST['sort']) {
            $args['order'] = array($sort, $sort_type);
        }
        $args['limit'] = array($start, $limit);

        $results = $stFacebookToolbox_model->getRecords($args);
        $total = $stFacebookToolbox_model->countRecords();
        $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName);

        $columns = array(
            'DiscountTypeID' => __('ID', $this->config['plugin_name']),
            'DiscountTypeName' => __('Name', $this->config['plugin_name']),
            'DiscountTypeCalculation' => __('Calculation', $this->config['plugin_name']),
        );
        register_column_headers('stFacebookToolbox_stFacebookToolbox', $columns);

        //initialize variable to view
        $this->view->results = $results;
        $this->view->pagination = $pagination;
    }
    
    public function gallery_setting() {
        global $current_user;
        if (isset($_GET['response'])) {
            $op = $this->option;
            $op['gallery_setting']['response'] = stripslashes($_GET['response']);
            $array = json_decode(stripslashes($_GET['response']));
            $op['gallery_setting']['id'] = $array->auth->user->nsid;
            $op['gallery_setting']['set'] = 'yahoo';
            $this->updateOption($op);
            echo "<script>window.location = '" . get_bloginfo('url') . "/wp-admin/admin.php?page=stFacebookToolbox&action=gallery_setting';</script>";
        }
        if (isset($_POST['data'])) {
            $options = $this->option;
            $option = $options['gallery_setting'];
            $op['gallery_setting']['response'] = $option['response'];
            $op['gallery_setting']['id'] = $_POST['data']['id'];
            $op['gallery_setting']['version'] = $_POST['data']['version'];
            //$op['gallery_setting']['embed'] = stripslashes($_POST['data']['embed']);
            $op['gallery_setting']['set'] = $_POST['data']['set'];
            $op['gallery_setting']['background'] = $_POST['data']['upload_file'];
            $this->updateOption($op);
            $arg = array(
                'status' => 'success',
                'message' => __('Save successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));
            die;
        }
        $options = $this->option;
        $this->view->option = $options['gallery_setting'];
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Gallery';
        $this->view->user_id = $current_user->ID;
        $string = stripslashes($_GET['response']);
    }

    public function gallery_album() {
        global $wpdb, $current_user;
        if ($_REQUEST['short_action'] == 'delete') {
            $wpdb->query("DELETE FROM st_ap_album WHERE id = " . $_POST['id'] . " AND user_id = " . $current_user->ID);
            $wpdb->query("DELETE FROM st_gallery_album WHERE album_id = " . $_POST['id'] . " AND user_id = " . $current_user->ID);
            $arg = array(
                'status' => 'success',
                'message' => __('Delete successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));
        }
        if (isset($_POST['data'])) {
            $data['name'] = $_POST['data']['name'];
            $data['facebook_id'] = $_POST['data']['facebook_id'];
            $data['flick_id'] = $_POST['data']['flick_id'];
            $data['user_id'] = $current_user->ID;
            if (intval($_POST['data']['id']) > 0) {
                $wpdb->update('st_ap_album', $data, array('id' => $_POST['data']['id']));
                $arg = array(
                    'status' => 'success',
                    'message' => __('Edit album successfully', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg), 'gallery_album');
                die;
            } else {
                $wpdb->insert('st_ap_album', $data);
                $arg = array(
                    'status' => 'success',
                    'message' => __('Album added successfully', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg), 'gallery_album');
                die;
            }
        }
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Gallery';
        $stFacebookToolbox_model = $this->loadmodel("stFacebookAlbum");
        $args = array();
        $args['where'] = ' user_id = ' . $current_user->ID;
        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;

        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 0;
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 0;
        if ($_REQUEST['sort']) {
            $args['order'] = array($sort, $sort_type);
        }
        $args['limit'] = array($start, $limit);

        $results = $stFacebookToolbox_model->getRecords($args);
        $total = $stFacebookToolbox_model->countRecords();
        $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName);

        $columns = array(
            'id' => __('ID', $this->config['plugin_name']),
            'name' => __('Name', $this->config['plugin_name']),
            'flick_id' => __('Flickr', $this->config['plugin_name']),
            'facebook_id' => __('Link to Facebook', $this->config['plugin_name']),
            'user_id' => __('Embedded code', $this->config['plugin_name']),
        );
        register_column_headers('stFacebookToolbox_stFacebookToolbox', $columns);

        //initialize variable to view
        $this->view->results = $results;
        $this->view->pagination = $pagination;
        $this->view->page = $wpdb->get_results("SELECT * FROM st_likepluginfbpagelist WHERE user_id = " . $current_user->ID . " AND pageid NOT IN (SELECT facebook_id FROM st_ap_album WHERE user_id = {$current_user->ID})");
        $this->view->model = $this->loadmodel("stFacebookAlbum");
    }

    public function home_applications() {
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Facebook Applications';
        $this->view->functions = $this->functions;
    }

    public function add_new_form() {
        global $wpdb, $current_user;
        if (isset($_POST['lastid'])) {
            echo $wpdb->get_var("SELECT MAX(form_id) FROM st_ap_forms WHERE user_id = " . $current_user->ID);
            die;
        }
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Form Builder';
        $this->view->iconNew = 'Home';
        $this->view->iconAction = "loadPage('applications');";
        $this->view->page = $wpdb->get_results("SELECT * FROM st_likepluginfbpagelist WHERE user_id = " . $current_user->ID . " AND pageid NOT IN (SELECT page_id FROM st_ap_forms)");
        $this->view->default_id = intval($wpdb->get_var("SELECT MAX(form_id) FROM st_ap_forms WHERE user_id = " . $current_user->ID)) + 1;
        if (isset($_POST['json'])) {
            $json = (json_decode(stripslashes($_POST['json'])));
            $data['form_description'] = $json->form_description;
            $data['form_name'] = $json->form_name;
            $data['button_label'] = $json->button_label;
            $data['form_redirect'] = $json->form_redirect;
            $data['form_success_message'] = $json->form_success_message;
            $data['user_id'] = $current_user->ID;
            $data['page_id'] = $json->page_id;
            $data['form_email'] = $json->form_email;
            $data['email_style'] = $json->email_style;
            $data['title_color'] = $json->title_color;
            $data['background_color_setting'] = $json->background_color_setting;
            $data['text_color_setting'] = $json->text_color_setting;
            $data['submit_button_color'] = $json->submit_button_color;
            $data['submit_button_text_color'] = $json->submit_button_text_color;
            $data['font_type'] = $json->font_type;
            $data['title_font_size'] = $json->title_font_size;
            $data['text_font_size'] = $json->text_font_size;
            $data['submit_font_size'] = $json->submit_font_size;
            $data['form_captcha'] = $json->has_captcha;
            $data['secrect_code'] = $this->genRandomString();
            $wpdb->insert('st_ap_forms', $data);
            $form_id = $wpdb->get_var("SELECT MAX(form_id) FROM st_ap_forms WHERE user_id = " . $current_user->ID);
            foreach ($json->element as $key => $value) {
                $element = array();
                $element['form_id'] = $form_id;
                $element['element_title'] = $value->element_title;
                $element['element_guidelines'] = $value->element_guidelines;
                $element['element_size'] = $value->element_size;
                $element['element_is_required'] = $value->element_is_required;
                $element['element_type'] = $value->element_type;
                $element['element_default_value'] = $value->element_default_value;
                $element['element_horizontal'] = $value->element_horizontal;
                $element['user_id'] = $current_user->ID;
                $element['element_id'] = $key;
                $wpdb->insert('st_ap_form_elements', $element);
                $wpdb->query("DELETE FROM st_ap_element_options WHERE form_id = {$form_id} AND element_id = " . $key);
                $wpdb->query("DELETE FROM st_ap_element_matrix WHERE form_id = {$form_id} AND element_id = " . $key);
                if (count($value->option) > 0)
                    foreach ($value->option as $ke => $va) {
                        $option = array();
                        if ($value->element_type == 'option') {
                            $option['form_id'] = $form_id;
                            $option['element_id'] = $key;
                            $option['option_id'] = $ke;
                            $option['option_column'] = $va->option_column;
                            $option['option_row'] = $va->option_row;
                            $option['user_id'] = $current_user->ID;
                            $wpdb->insert('st_ap_element_matrix', $option);
                        } else {
                            $option['form_id'] = $form_id;
                            $option['element_id'] = $key;
                            $option['option_id'] = $ke;
                            $option['option'] = $va->option;
                            $option['option_is_default'] = $va->option_is_default;
                            $option['user_id'] = $current_user->ID;
                            $wpdb->insert('st_ap_element_options', $option);
                        }
                    }
            }
            $arg = array(
                'status' => 'success',
                'message' => __('Save successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));
            die;
        }
    }

    public function edit_form() {
        global $wpdb, $current_user;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Form Builder';
        $this->view->iconNew = 'Home';
        $this->view->iconAction = "loadPage('applications');";
        $this->view->form = $wpdb->get_row("SELECT * FROM st_ap_forms WHERE form_id = " . intval($_POST['id']));
        $this->view->page = $wpdb->get_results("SELECT * FROM st_likepluginfbpagelist WHERE user_id = " . $current_user->ID . " AND pageid NOT IN (SELECT page_id FROM st_ap_forms WHERE form_id <> " . intval($_POST['id']) . ")");
        $this->view->result = $wpdb->get_results("SELECT * FROM st_ap_form_elements WHERE form_id = " . intval($_POST['id']) . " ORDER BY element_sort,element_id ASC");
        $this->view->wpdb = $wpdb;
        $this->view->count = $wpdb->get_var("SELECT MAX(element_id) FROM st_ap_form_elements WHERE form_id = " . intval($_POST['id']));
        $this->view->properties = $_POST['view'];
        $this->view->show_style = $_POST['style'];
        if (isset($_POST['redirect'])) {
            $arg = array(
                'status' => 'success',
                'message' => __('Save successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));
        }
        if (isset($_POST['json'])) {

            //----------------------
            $json = (json_decode(stripslashes($_POST['json'])));
            $wpdb->query("DELETE FROM st_ap_form_elements WHERE form_id = " . intval($json->form_id));
            $wpdb->query("DELETE FROM st_ap_element_options WHERE form_id = {$json->form_id}");
            $wpdb->query("DELETE FROM st_ap_element_matrix WHERE form_id = {$json->form_id}");
            $data['form_description'] = $json->form_description;
            $data['form_name'] = $json->form_name;
            $data['form_captcha'] = $json->has_captcha;
            $data['button_label'] = $json->button_label;
            $data['form_redirect'] = $json->form_redirect;
            $data['form_success_message'] = $json->form_success_message;
            $data['background_color_setting'] = $json->background_color_setting;
            $data['text_color_setting'] = $json->text_color_setting;
            $data['submit_button_color'] = $json->submit_button_color;
            $data['submit_button_text_color'] = $json->submit_button_text_color;
            $data['font_type'] = $json->font_type;
            $data['title_font_size'] = $json->title_font_size;
            $data['text_font_size'] = $json->text_font_size;
            $data['submit_font_size'] = $json->submit_font_size;
            $data['user_id'] = $current_user->ID;
            $data['page_id'] = $json->page_id;
            $data['form_email'] = $json->form_email;
            $data['email_style'] = $json->email_style;
            $data['title_color'] = $json->title_color;
            $form_id = $json->form_id;
            $wpdb->update('st_ap_forms', $data, array('form_id' => $json->form_id));
            foreach ($json->element as $key => $value) {
                $element = array();
                $element['form_id'] = $form_id;
                $element['element_title'] = $value->element_title;
                $element['element_guidelines'] = $value->element_guidelines;
                $element['element_size'] = $value->element_size;
                $element['element_is_required'] = $value->element_is_required;
                $element['element_type'] = $value->element_type;
                $element['element_default_value'] = $value->element_default_value;
                $element['element_horizontal'] = $value->element_horizontal;
                $element['user_id'] = $current_user->ID;
                $element['element_id'] = $key;
                $wpdb->insert('st_ap_form_elements', $element);
                if (count($value->option) > 0)
                    foreach ($value->option as $ke => $va) {
                        $option = array();
                        if ($value->element_type == 'option') {
                            $option['form_id'] = $form_id;
                            $option['element_id'] = $key;
                            $option['option_id'] = $ke;
                            $option['option_column'] = $va->option_column;
                            $option['option_row'] = $va->option_row;
                            $option['user_id'] = $current_user->ID;
                            $wpdb->insert('st_ap_element_matrix', $option);
                        } else {
                            $option['form_id'] = $form_id;
                            $option['element_id'] = $key;
                            $option['option_id'] = $ke;
                            $option['option'] = $va->option;
                            $option['option_is_default'] = $va->option_is_default;
                            $option['user_id'] = $current_user->ID;
                            $wpdb->insert('st_ap_element_options', $option);
                        }
                    }
            }
            $arg = array(
                'status' => 'success',
                'message' => __('Edit successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));
            die;
            //----------------------
            $wpdb->update('st_ap_forms', $data, array('form_id' => $_POST['form_id']));
        }
    }

    public function view_form_entries() {
        global $wpdb;
        if ($_REQUEST['short_action'] == 'delete') {

            $wpdb->query("DELETE FROM st_ap_form_value WHERE id = " . $_POST['id']);
            $arg = array(
                'status' => 'success',
                'message' => __('Delete successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));
        }
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Form Builder';
        $this->view->iconNew = 'Home';
        $this->view->iconAction = "loadPage('applications');";
        $this->view->result = $wpdb->get_results("SELECT * FROM st_ap_form_value WHERE form_id=" . $_POST['form_id'] . " ORDER BY id DESC");
        $this->view->menu = $wpdb->get_results("SELECT * FROM st_ap_form_elements WHERE form_id=" . $_POST['form_id'] . " AND element_type <> 'break' AND display_entries = 1");
        $this->view->default_id = $_POST['form_id'];
    }

    public function entries_display_option() {
        global $wpdb;
        if ($_POST['form_id'] != '') {
            $wpdb->update('st_ap_form_elements', array('display_entries' => 0), array('form_id' => $_POST['form_id']));
            foreach ($_POST['data'] as $key => $value) {
                $wpdb->update('st_ap_form_elements', array('display_entries' => 1), array('form_id' => $_POST['form_id'], 'element_id' => $key));
            }
        }
        $this->view->id = $_POST['id'];
        $this->view->result = $wpdb->get_results("SELECT * FROM st_ap_form_elements WHERE form_id = " . $_POST['id'] . " AND element_type <> 'break'");
    }

    public function entries_csv_option() {
        global $wpdb;
        $this->view->pluginPath = $this->config['pluginPath'];
        $this->view->id = $_POST['id'];
        $this->view->result = $wpdb->get_results("SELECT * FROM st_ap_form_elements WHERE form_id = " . $_POST['id'] . " AND element_type <> 'break'");
    }

    public function view_form_popup() {
        global $wpdb;
        if (isset($_POST['view'])) {
            $this->view->result = json_decode($wpdb->get_var("SELECT json FROM st_ap_form_value WHERE id = " . $_POST['view']));
            $result = $wpdb->get_results("SELECT element_title FROM st_ap_form_elements WHERE form_id = " . intval($_POST['id']) . " AND display_entries = 1 AND element_type <> 'break'");
            foreach ($result as $row) {
                $array[] = $row->element_title;
            }
            $this->view->array = $array;
        }
    }

    public function view_form() {
        echo '<iframe src="' . get_bloginfo('url') . '/wp-content/plugins/stSocialMediaToolbox/Toolboxes/stFacebookToolbox/view_form/index.php?id=' . $_GET['id'] . '" marginheight="0" marginwidth="0" frameborder="0" scrolling="auto" width="100%" height="100%">
  <p>Your browser does not support iframes.</p>
</iframe>';
    }

    protected function genRandomString() {
        $length = 10;
        $characters = "0123456789abcdefghijklmnopqrstuvwxyz";
        $string = "";

        for ($p = 0; $p < $length; $p++) {
            $string .= $characters[mt_rand(0, strlen($characters))];
        }

        return $string;
    }

    public function save_form() {
        global $wpdb, $current_user;
        $json = (json_decode(stripslashes($_POST['json'])));
        $data['form_description'] = $json->form_description;
        $data['form_name'] = $json->form_name;
        $data['button_label'] = $json->button_label;
        $data['form_redirect'] = $json->form_redirect;
        $data['form_success_message'] = $json->form_success_message;
        $data['user_id'] = $current_user->ID;
        $data['page_id'] = $json->page_id;
        $data['form_email'] = $json->form_email;
        $data['email_style'] = $json->email_style;
        $data['title_color'] = $json->title_color;
        $data['background_color_setting'] = $json->background_color_setting;
        $data['text_color_setting'] = $json->text_color_setting;
        $data['submit_button_color'] = $json->submit_button_color;
        $data['submit_button_text_color'] = $json->submit_button_text_color;
        $data['font_type'] = $json->font_type;
        $data['title_font_size'] = $json->title_font_size;
        $data['text_font_size'] = $json->text_font_size;
        $data['submit_font_size'] = $json->submit_font_size;
        $data['secrect_code'] = $this->genRandomString();
        $wpdb->insert('st_ap_forms', $data);
        $form_id = $wpdb->get_var("SELECT MAX(form_id) FROM st_ap_forms WHERE user_id = " . $current_user->ID);
        foreach ($json->element as $key => $value) {
            $element = array();
            $element['form_id'] = $form_id;
            $element['element_title'] = $value->element_title;
            $element['element_guidelines'] = $value->element_guidelines;
            $element['element_size'] = $value->element_size;
            $element['element_is_required'] = $value->element_is_required;
            $element['element_type'] = $value->element_type;
            $element['element_default_value'] = $value->element_default_value;
            $element['element_horizontal'] = $value->element_horizontal;
            $element['user_id'] = $current_user->ID;
            $element['element_id'] = $key;
            $wpdb->insert('st_ap_form_elements', $element);
            $wpdb->query("DELETE FROM st_ap_element_options WHERE form_id = {$form_id} AND element_id = " . $key);
            $wpdb->query("DELETE FROM st_ap_element_matrix WHERE form_id = {$form_id} AND element_id = " . $key);
            if (count($value->option) > 0)
                foreach ($value->option as $ke => $va) {
                    $option = array();
                    if ($value->element_type == 'option') {
                        $option['form_id'] = $form_id;
                        $option['element_id'] = $key;
                        $option['option_id'] = $ke;
                        $option['option_column'] = $va->option_column;
                        $option['option_row'] = $va->option_row;
                        $option['user_id'] = $current_user->ID;
                        $wpdb->insert('st_ap_element_matrix', $option);
                    } else {
                        $option['form_id'] = $form_id;
                        $option['element_id'] = $key;
                        $option['option_id'] = $ke;
                        $option['option'] = $va->option;
                        $option['option_is_default'] = $va->option_is_default;
                        $option['user_id'] = $current_user->ID;
                        $wpdb->insert('st_ap_element_options', $option);
                    }
                }
        }
        $arg = array(
            'status' => 'success',
            'message' => __('Save successful', $config['plugin_name'])
        );
        echo $this->functions->sendMessage(json_encode($arg));
    }

    public function delete_element() {
        global $wpdb, $current_user;
        $wpdb->query("DELETE FROM st_ap_form_elements WHERE form_id = " . intval($_POST['form_id']) . " AND element_id = " . intval($_POST['element_id']));
        $wpdb->query("DELETE FROM st_ap_element_options WHERE form_id = " . intval($_POST['form_id']) . " AND element_id = " . intval($_POST['element_id']));
        $wpdb->query("DELETE FROM st_ap_element_matrix WHERE form_id = " . intval($_POST['form_id']) . " AND element_id = " . intval($_POST['element_id']));
        die;
    }

    public function delete_form() {
        global $wpdb;
        $id = $_POST['id'];
        $wpdb->query("DELETE FROM st_ap_form_elements WHERE form_id = " . intval($id));
        $wpdb->query("DELETE FROM st_ap_element_options WHERE form_id = " . intval($id));
        $wpdb->query("DELETE FROM st_ap_element_matrix WHERE form_id = " . intval($id));
        $wpdb->query("DELETE FROM st_ap_form_value WHERE form_id = " . intval($id));
        $wpdb->query("DELETE FROM st_ap_forms WHERE form_id = " . intval($id));
        $arg = array(
            'status' => 'success',
            'message' => __('The selected form was successfully deleted', $config['plugin_name'])
        );
        echo $this->functions->sendMessage(json_encode($arg));
        die;
    }

    public function save_element() {
        global $wpdb, $current_user;
        $data['form_id'] = $_POST['form_id'];
        $data['element_title'] = $_POST['element_title'];
        $data['element_guidelines'] = $_POST['element_guidelines'];
        $data['element_size'] = $_POST['element_size'];
        $data['element_is_required'] = $_POST['element_is_required'];
        $data['element_type'] = $_POST['element_type'];
        $data['element_default_value'] = $_POST['element_default_value'];
        $data['user_id'] = $current_user->ID;
        $data['element_id'] = $_POST['element_id'];
        $wpdb->insert('st_ap_form_elements', $data);

        $wpdb->query("DELETE FROM st_ap_element_options WHERE form_id = {$_POST['form_id']} AND element_id = " . $_POST['element_id']);
        $wpdb->query("DELETE FROM st_ap_element_matrix WHERE form_id = {$_POST['form_id']} AND element_id = " . $_POST['element_id']);
        echo 'success';
        die;
    }

    public function embed_code() {
        global $wpdb;
        $this->view->id = $_POST['id'];
        $this->view->key = $wpdb->get_var('SELECT secrect_code FROM st_ap_forms WHERE form_id = ' . intval($_POST['id']));
    }

    public function gallery_embed() {
        $this->view->id = $_POST['id'];
    }

    public function save_option() {
        global $wpdb, $current_user;
        $element_id = $_POST['element_id'];
        $data['form_id'] = $_POST['form_id'];
        $data['element_id'] = $element_id;
        $data['option_id'] = $_POST['option_id'];
        $data['option'] = $_POST['option'];
        $data['option_is_default'] = $_POST['option_is_default'];
        $data['user_id'] = $current_user->ID;
        if ($wpdb->get_var("SELECT * FROM st_ap_element_options WHERE form_id = {$_POST['form_id']} AND element_id = {$element_id} AND option_id = {$_POST['option_id']}") == 0) {
            $wpdb->insert('st_ap_element_options', $data);
        } else {
            $wpdb->update('st_ap_element_options', $data, array('element_id' => $element_id, 'form_id' => $_POST['form_id'], 'option_id' => $_POST['option_id']));
        }
    }

    public function save_matrix() {
        global $wpdb, $current_user;
        if (isset($_POST['realid'])) {
            $element_id = $_POST['realid'];
        } else {
            $element_id = $_POST['element_id'];
        }
        $data['form_id'] = $_POST['form_id'];
        $data['element_id'] = $element_id;
        $data['option_id'] = $_POST['option_id'];
        $data['option_column'] = $_POST['option_column'];
        $data['option_row'] = $_POST['option_row'];
        $data['user_id'] = $current_user->ID;
        if ($wpdb->get_var("SELECT * FROM st_ap_element_matrix WHERE form_id = {$_POST['form_id']} AND element_id = {$element_id} AND option_id = {$_POST['option_id']}") == 0) {
            $wpdb->insert('st_ap_element_matrix', $data);
        } else {
            $wpdb->update('st_ap_element_matrix', $data, array('element_id' => $element_id, 'form_id' => $_POST['form_id'], 'option_id' => $_POST['option_id']));
        }
    }

    public function facebook_image_map() {
        global $wpdb, $current_user;
        if (isset($_POST['id'])) {
            $wpdb->query("DELETE FROM st_facebookimagemap WHERE id=" . $_POST['id']);
            $arg = array(
                'status' => 'success',
                'message' => __('Delete successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));
            die;
        }
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Facebook tools';
        $options = $this->option;
        $this->view->option = $option = $options['facebook_image_map'];
        $this->view->result = $wpdb->get_results("SELECT * FROM st_facebookimagemap WHERE user_id=" . $current_user->ID);
        if (isset($_POST['image'])) {
            $option['facebook_image_map']['image'] = $_POST['image'];
            $this->updateOption($option);
            //update_option('facebook_image_map',array('image'=>$_POST['image']));
        }
        if (isset($_POST['data']) AND $_POST['data']['title'] != '') {
            extract($_POST['data']);
            $wpdb->insert('st_facebookimagemap', array('begin' => $x1 . ':' . $y1, 'end' => $x2 . ':' . $y2, 'width' => $width, 'height' => $height, 'title' => $title, 'link' => $url, 'user_id' => $current_user->ID));
        }
    }

    public function display_facebook_pages() {
        define('APP_API_KEY', $this->config['facebook_api_key']);
        define('APP_SECRET_KEY', $this->config['facebook_secret']);
        define('APP_ID', $this->config['facebook_app_id']);
        $options = $this->option;
        $option = $options['facebook_tab'];
        $page_site = str_replace('http://apps.facebook.com/', '', $this->config['facebook_app_url']);
        $page_site = str_replace('/', '', $page_site);
        $page_title = urlencode($this->config['page_title']);
        $page = get_page($option['pageid']);
        $args = array(
            'page_id' => $option['pageid'],
        );
        query_posts($args);
        $this->view->page_title = $page_title;
        $this->view->page_site = $page_site;
        $this->view->option = $option;
        $this->view->post = get_post($option['pageid']);
    }

    public function display_facebook_wall($args) {
        define('APP_API_KEY', $this->config['facebook_api_key']);
        define('APP_SECRET_KEY', $this->config['facebook_secret']);
        define('APP_ID', $this->config['facebook_app_id']);
        require_once $this->config['classDir'] . 'facebook/facebook.php';
        $facebook = new Facebook(APP_API_KEY, APP_SECRET_KEY, true);
        $pageId = $args['pageid'];
        $offset = empty($args['offset']) ? 0 : $args['offset'];
        if (!empty($pageId)) {
            $num_post = empty($args['posts']) ? 1 + $offset : $args['posts'] + $offset;
            $infos = $facebook->api_client->stream_get(0, $pageId, null, null, $num_post);
            $result = $infos['posts'];
            $profiles = $infos['profiles'];
            $users = array();
            foreach ($profiles as $pr) {
                $users[$pr['id']] = $pr;
            }
        } else {
            $result = false;
            $users = false;
        }
        $this->view->result = $result;
        $this->view->users = $users;
        $this->view->offset = $offset;
        $this->view->infos = $infos;
    }

    public function display_facebook_feeds() {
        global $wpdb;
        if (isset($_GET['id'])) {
            $time = date('Y-m-d');
            $count = $wpdb->get_var("SELECT COUNT(*) FROM st_facebook_feed WHERE post_id=" . $_REQUEST['id']);
            if ($count == 0) {
                $data = array('post_id' => $_REQUEST['id'], 'ip' => $this->functions->getClientIp(), 'cdate' => $time, 'likes' => 1);
                $wpdb->insert("st_facebook_feed", $data);
            } else {
                $likes = $wpdb->get_var("SELECT likes FROM st_facebook_feed WHERE post_id=" . $_REQUEST['id']);
                $likes = $likes + 1;
                $data = array('post_id' => $_REQUEST['id'], 'ip' => $this->functions->getClientIp(), 'cdate' => $time, 'likes' => $likes);
                $wpdb->update("st_facebook_feed", $data, array('post_id' => $_REQUEST['id']));
            }
        }
        $stFacebookToolbox_model = $this->loadmodel("stFacebookFeed");
        $options = $this->option;
        $this->view->option = $options['facebook_feed'];
        $this->view->tab = $options['facebook_tab'];
        // Prepare for google analytics
        $page_site = str_replace('http://apps.facebook.com/', '', $this->config['facebook_app_url']);
        $page_site = str_replace('/', '', $page_site);
        $page_title = urlencode($this->config['page_title']);
        $this->view->page_site = $page_site;
        $this->view->page_title = $page_title;
        $this->view->model = $stFacebookToolbox_model;
        $this->view->categories = $options['facebook_feed_category'];
    }

    public function dashboard() {
        $option = $this->option;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Dashboard';
        $this->view->iconNew = 'Add new';
        $this->view->iconAction = "add_dashboard();";
        $this->view->option = $option['facebook_dashboard'];
        if ($_POST['delete'] == 'true') {
            $options = $option['facebook_dashboard'];
            foreach ($options as $row) {
                if ($row != $_POST['id']) {
                    $mang[] = $row;
                }
            }
            $option['facebook_dashboard'] = $mang;
            $this->updateOption($option);


            $arg = array(
                'status' => 'success',
                'message' => __('Delete successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));
        }
        if (isset($_POST['box'])) {
            $option['facebook_dashboard'][] = $_POST['box'];
            $this->updateOption($option);
            $arg = array(
                'status' => 'success',
                'message' => __('Add successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));
        }
        $stFacebookToolbox_model = $this->loadmodel("stFacebookDashboard");
        $stFacebookToolbox_model->return_dashboard();
        $this->view->model = $stFacebookToolbox_model;
        $this->view->option = $option;
        $this->view->functions = $this->functions;
    }

    public function facebook_pages() {
        global $wpdb, $current_user;
        $stFacebookToolbox_model = $this->loadmodel("stFacebookPage");

        // short action handle
        if ($_REQUEST['short_action'] == 'delete') {

            $wpdb->query("DELETE FROM st_likepluginfbpagelist WHERE pageid = " . $_POST['id'] . " AND user_id = " . $current_user->ID);
            $arg = array(
                'status' => 'success',
                'message' => __('Delete successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));
        }

        $args = array();
        $args['where'] = ' pageid != "" AND user_id = ' . $current_user->ID;
        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;

        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 0;
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 0;
        if ($_REQUEST['sort']) {
            $args['order'] = array($sort, $sort_type);
        }
        $args['limit'] = array($start, $limit);

        $results = $stFacebookToolbox_model->getRecords($args);
        $args['limit'] = '';
        $total = $stFacebookToolbox_model->countRecords($args);
        //$total = $wpdb->get_var("SELECT COUNT(*) FROM st_likepluginfbpagelist WHERE ".$args['where']);
        $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName);
        $columns = array(
            'pageid' => __('PageID', $this->config['plugin_name']),
            'pagename' => __('Page Name', $this->config['plugin_name']),
            'pagepictureurl' => __('Page Profile Picture', $this->config['plugin_name']),
            'pageurl' => __('Page URL', $this->config['plugin_name']),
            'fancount' => __('Number of fans', $this->config['plugin_name']),
        );
        register_column_headers('stFacebookToolbox_stFacebookToolbox', $columns);

        //initialize variable to view
        $this->view->results = $results;
        $this->view->pagination = $pagination;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Facebook pages';
        $this->view->iconNew = 'Add New Page';
        $this->view->iconAction = "loadPage('add_facebook_page')";
        $this->view->model = $stFacebookToolbox_model;
        //$this->view->viewNew = 'stFacebookToolboxEdit';
    }

    public function add_facebook_page() {
        global $wpdb, $current_user;
        $stFacebookToolbox_model = $this->loadmodel("stFacebookPage");

        //initialize variable to view
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Add Facebook page';
        $this->view->user_id = $current_user->ID;
        if (isset($_POST['id'])) {
            $pageid = json_decode(file_get_contents("http://graph.facebook.com/" . $_POST['id']));
            if ($wpdb->get_var("SELECT COUNT(pageid) FROM st_likepluginfbpagelist WHERE pageid=" . $pageid->id . " AND user_id <> " . $current_user->ID) > 0) {
                $arg = array(
                    'status' => 'error',
                    'message' => __('Page is existed in system', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg));
                $this->view->id = $pageid->id;
            } else {
                $this->view->pageid = $pageid;
                $this->view->id = $pageid->id;
                if ($wpdb->get_var("SELECT COUNT(pageid) FROM st_likepluginfbpagelist WHERE pageid=" . $_POST['id']) > 0) {
                    $this->view->headTitle1 = 'Edit Facebook page';
                }
            }
        }
        // Handle post
        if ($_POST['data']) {
            if ($wpdb->get_var("SELECT COUNT(pageid) FROM st_likepluginfbpagelist WHERE pageid=" . $_POST['data']['pageid']) > 0) {
                $wpdb->update("st_likepluginfbpagelist", $_POST['data'], array('pageid' => $_POST['data']['pageid']));
            } else {
                $wpdb->insert("st_likepluginfbpagelist", $_POST['data']);
            }
        }
    }

    public function page_analytics() {
        global $current_user;
        $stFacebookToolbox_model = $this->loadmodel("stFacebookPage");
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Page Analytics';
        $args = array();

        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;

        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 0;
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 0;
        if ($_REQUEST['sort']) {
            $args['order'] = array($sort, $sort_type);
        } else {
            $args['order'] = array('pageid', 'DESC');
        }
        $args['where'] = ' pageid != "" AND user_id=' . $current_user->ID;
        $args['limit'] = array($start, $limit);

        $results = $stFacebookToolbox_model->getRecords($args);
        $args['limit'] = '';
        $total = $stFacebookToolbox_model->countRecords($args);

        $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName);

        $columns = array(
            'pagepictureurl' => __('Profile Picture', $this->config['plugin_name']),
            'pagename' => __('Page name', $this->config['plugin_name']),
            'fancount' => __('Number of fans', $this->config['plugin_name']),
        );
        register_column_headers('stFacebookToolbox_stFacebookToolbox', $columns);

        //initialize variable to view
        $this->view->results = $results;
        $this->view->pagination = $pagination;
        $this->view->model = $stFacebookToolbox_model;
    }

    public function fan_list() {
        global $wpdb, $current_user;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Page Analytics';
        if (isset($_POST['pageid']) && intval($_POST['pageid']) != 'all') {
            $where = 'uid IN (SELECT fanuserid FROM st_fanofpage WHERE pageid="' . $_POST['pageid'] . '" AND user_id = ' . $current_user->ID . ')';
        } else {
            $where = ' uid IN (SELECT fanuserid FROM st_fanofpage WHERE user_id = ' . $current_user->ID . ' )';
        }
        $gender = (isset($_POST['gender'])) ? intval($_POST['gender']) : 1;
        switch ($gender) {
            case '2':
                $where .= ' AND sex="male"';
                break;
            case '3':
                $where .= ' AND sex="female"';
                break;
            case '4':
                $where .= ' AND (sex <> "female" AND sex <> "male")';
                break;
        }
        if (isset($_POST['locale']) && $_POST['locale'] != 'all') {
            $where .= ' AND locale="' . $_POST['locale'] . '"';
        }
        $stFacebookToolbox_model = $this->loadmodel("stFacebookUser");
        $args = array();
        $args['where'] = $where;
        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;

        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 'firstname';
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 'ASC';
        if ($sort) {
            $args['order'] = array($sort, $sort_type);
        } else {
            $args['order'] = array('firstname', 'DESC');
        }
        $args['limit'] = array($start, $limit);

        $results = $stFacebookToolbox_model->getRecords($args);
        $total = $wpdb->get_var("SELECT COUNT(*) FROM st_likepluginfbusers WHERE " . $args['where']);
        $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName);
        $columns = array(
            'profileurl' => __('Profile Picture', $this->config['plugin_name']),
            'firstname' => __('First name', $this->config['plugin_name']),
            'lastname' => __('Last name', $this->config['plugin_name']),
            'sex' => __('Sex', $this->config['plugin_name']),
            'locale' => __('Locale', $this->config['plugin_name']),
        );
        register_column_headers('stFacebookToolbox_stFacebookToolbox', $columns);

        //initialize variable to view
        $this->view->results = $results;
        $this->view->pagination = $pagination;
        $this->view->model = $stFacebookToolbox_model;
        $this->view->page = $wpdb->get_results("SELECT * FROM st_likepluginfbpagelist WHERE pageid != '' AND user_id = " . $current_user->ID);
        $this->view->locale = $wpdb->get_results("SELECT locale FROM st_likepluginfbusers WHERE user_id = " . $current_user->ID . " GROUP BY locale");
        $this->view->dpage = $_POST['pageid'];
        $this->view->dlocale = $_POST['locale'];
        $this->view->dgender = $_POST['gender'];
    }

    public function fan_count() {
        global $wpdb, $current_user;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Page Analytics <img src="'.$this->config['imagesUrl'].'pdf.png" style="cursor:pointer;margin-bottom: -8px;width: 24px;float:right;margin-right:10px;" onclick="make_pdf();" /><img src="'.$this->config['imagesUrl'].'excel.png" style="cursor:pointer;margin-bottom: -8px;width: 24px;float:right;margin-right:10px;" onclick="make_excel();" />';
        $this->view->page = $wpdb->get_results("SELECT * FROM st_likepluginfbpagelist WHERE user_id = " . $current_user->ID);
        $id = (isset($_POST['pageid'])) ? $_POST['pageid'] : $wpdb->get_var("SELECT pageid FROM st_likepluginfbpagelist WHERE user_id=" . $current_user->ID);
        $month = (isset($_POST['month'])) ? $_POST['month'] : date('m');
        $year = (isset($_POST['year'])) ? $_POST['year'] : date('Y');
        $timestamp = mktime(0, 0, 0, $month, 1, $year);
        $dates = date(t, $timestamp);
        $b_likes = 0;
        $b_shares = 0;
        $b_comments = 0;
        $b_posts = 0;
        $b_users = 0;
        $check = 0;
        $b_fancount = 0;
        for ($i = 1; $i <= $dates; $i++) {
            $day = ($i < 10) ? '0' . $i : $i;
            $array_date[] = '"' . $day . '-' . $month . '-' . $year . '"';
        }
        $where = implode(",", $array_date);
        $where2 = ' AND fancount > 0';
        $where_id = 'WHERE facebookpageid="' . $id . '"';
        $start = $wpdb->get_row("SELECT * FROM st_likepluginfbpagestatistics {$where_id} AND date IN (" . $where . ")" . $where2 . "  ORDER BY date LIMIT 0,1");
        $end = $wpdb->get_row("SELECT * FROM st_likepluginfbpagestatistics {$where_id} AND date IN (" . $where . ")" . $where2 . "  ORDER BY date DESC LIMIT 0,1");
        $myrows = $wpdb->get_results("SELECT * FROM st_likepluginfbpagestatistics {$where_id} AND date IN (" . $where . ") ORDER BY date ASC");
        foreach ($myrows as $result) {
            $row = $wpdb->get_row("SELECT * FROM st_likepluginfbpagelist WHERE pageid=" . $result->facebookpageid);

            $data['likes'] = $result->numberoflikes;
            $data['shares'] = $result->numberofshares;
            $data['comments'] = $result->numberofcomments;
            $data['posts'] = $result->numberofposts;
            $data['users'] = $result->numberofusers;
            $data['fancount'] = $result->fancount;
            $data['day'] = $result->date;
            $array[] = $data;
        }
        $this->view->chart = $array;
        $this->view->month = $month;
        $this->view->year = $year;
        $this->view->id = $id;
        $this->view->plugin_url = trailingslashit(WP_PLUGIN_URL . '/' . dirname(plugin_basename(__FILE__)));
        $this->view->month_name = $this->config['months'];
    }

    public function fan_count_daily_change() {
        global $wpdb, $current_user;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Page Analytics <img src="'.$this->config['imagesUrl'].'pdf.png" style="cursor:pointer;margin-bottom: -8px;width: 24px;float:right;margin-right:10px;" onclick="make_pdf();" /><img src="'.$this->config['imagesUrl'].'excel.png" style="cursor:pointer;margin-bottom: -8px;width: 24px;float:right;margin-right:10px;" onclick="make_excel();" />';
        $this->view->page = $wpdb->get_results("SELECT * FROM st_likepluginfbpagelist WHERE user_id = " . $current_user->ID);
        $id = (isset($_POST['pageid'])) ? $_POST['pageid'] : $wpdb->get_var("SELECT pageid FROM st_likepluginfbpagelist WHERE user_id=" . $current_user->ID);
        $month = (isset($_POST['month'])) ? $_POST['month'] : date('m');
        $year = (isset($_POST['year'])) ? $_POST['year'] : date('Y');
        $timestamp = mktime(0, 0, 0, $month, 1, $year);
        $dates = date(t, $timestamp);
        $b_likes = 0;
        $b_shares = 0;
        $b_comments = 0;
        $b_posts = 0;
        $b_users = 0;
        $check = 0;
        $b_fancount = 0;
        for ($i = 1; $i <= $dates; $i++) {
            $day = ($i < 10) ? '0' . $i : $i;
            $array_date[] = '"' . $day . '-' . $month . '-' . $year . '"';
        }
        $check2 = '"01-'.$month.'-'.$year.'"';
        if(in_array($check2,$array_date)){
            if($month == '01'){
                $month2 = '12';
                $year2 = $year-1;
            }
            else{
                $month2 = $month-1;
                $year2 = $year;
            }
            $time2 = mktime(0, 0, 0, $month2, 1, $year2);
            $dates2 = date(t,$time2);
            $result2 = $wpdb->get_row("SELECT * FROM st_likepluginfbpagestatistics WHERE facebookpageid=" . $id . " AND date = '$dates2-$month2-$year2'");
            $b_likes = $result2->numberoflikes;
            $b_shares = $result2->numberofshares;
            $b_comments = $result2->numberofcomments;
            $b_posts = $result2->numberofposts;
            $b_users = $result2->numberofusers;
            $b_fancount = $result2->fancount; 
        }
        $where = implode(",", $array_date);
        $where2 = ' AND fancount > 0';
        $start = $wpdb->get_row("SELECT * FROM st_likepluginfbpagestatistics WHERE facebookpageid=" . $id . $where2 . "  ORDER BY statiisticsid LIMIT 0,1");
        $end = $wpdb->get_row("SELECT * FROM st_likepluginfbpagestatistics WHERE facebookpageid=" . $id . " AND date IN (" . $where . ")" . $where2 . "  ORDER BY date DESC LIMIT 0,1");
        $myrows = $wpdb->get_results("SELECT * FROM st_likepluginfbpagestatistics WHERE facebookpageid=" . $id . " AND date IN (" . $where . ")");
        foreach ($myrows as $result) {
            $row = $wpdb->get_row("SELECT * FROM st_likepluginfbpagelist WHERE pageid=" . $result->facebookpageid);
            $data = array();
            if ($result->date != $start->date) {
                $data['likes'] = $result->numberoflikes - $b_likes;
                $data['shares'] = $result->numberofshares - $b_shares;
                $data['comments'] = $result->numberofcomments - $b_comments;
                $data['posts'] = $result->numberofposts - $b_posts;
                $data['users'] = $result->numberofusers - $b_users;
                $data['fancount'] = $result->fancount - $b_fancount;
                $data['day'] = $result->date;
                $array[] = $data;
                
            }
            $b_likes = $result->numberoflikes;
            $b_shares = $result->numberofshares;
            $b_comments = $result->numberofcomments;
            $b_posts = $result->numberofposts;
            $b_users = $result->numberofusers;
            $b_fancount = $result->fancount;
        }
        $this->view->chart = $array;
        $this->view->month = $month;
        $this->view->year = $year;
        $this->view->id = $id;
        $this->view->plugin_url = trailingslashit(WP_PLUGIN_URL . '/' . dirname(plugin_basename(__FILE__)));
        $this->view->month_name = $this->config['months'];
    }

    public function user_activity() {
        global $wpdb, $current_user;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Page Analytics <img src="'.$this->config['imagesUrl'].'pdf.png" style="cursor:pointer;margin-bottom: -8px;width: 24px;float:right;margin-right:10px;" onclick="make_pdf();" /><img src="'.$this->config['imagesUrl'].'excel.png" style="cursor:pointer;margin-bottom: -8px;width: 24px;float:right;margin-right:10px;" onclick="make_excel();" />';
        $this->view->page = $wpdb->get_results("SELECT * FROM st_likepluginfbpagelist WHERE user_id = " . $current_user->ID);
        $id = (isset($_POST['pageid'])) ? $_POST['pageid'] : $wpdb->get_var("SELECT pageid FROM st_likepluginfbpagelist WHERE user_id=" . $current_user->ID);
        $month = (isset($_POST['month'])) ? $_POST['month'] : date('m');
        $year = (isset($_POST['year'])) ? $_POST['year'] : date('Y');
        $timestamp = mktime(0, 0, 0, $month, 1, $year);
        $dates = date(t, $timestamp);
        $b_likes = 0;
        $b_shares = 0;
        $b_comments = 0;
        $b_posts = 0;
        $b_users = 0;
        $check = 0;
        $b_fancount = 0;
        for ($i = 1; $i <= $dates; $i++) {
            $day = ($i < 10) ? '0' . $i : $i;
            $array_date[] = '"' . $day . '-' . $month . '-' . $year . '"';
        }
        $where = implode(",", $array_date);
        $where2 = ' AND numberofusers > 0';
        $start = $wpdb->get_row("SELECT * FROM st_likepluginfbpagestatistics WHERE facebookpageid=" . $id . " AND date IN (" . $where . ")" . $where2 . "  ORDER BY date LIMIT 0,1");
        $end = $wpdb->get_row("SELECT * FROM st_likepluginfbpagestatistics WHERE facebookpageid=" . $id . " AND date IN (" . $where . ")" . $where2 . "  ORDER BY date DESC LIMIT 0,1");
        $myrows = $wpdb->get_results("SELECT * FROM st_likepluginfbpagestatistics WHERE facebookpageid=" . $id . " AND date IN (" . $where . ")");
        foreach ($myrows as $result) {
            $row = $wpdb->get_row("SELECT * FROM st_likepluginfbpagelist WHERE pageid=" . $result->facebookpageid);

            $data['likes'] = $result->numberoflikes;
            $data['shares'] = $result->numberofshares;
            $data['comments'] = $result->numberofcomments;
            $data['posts'] = $result->numberofposts;
            $data['users'] = $result->numberofusers;
            $data['fancount'] = $result->fancount;
            $data['day'] = $result->date;
            $array[] = $data;
        }
        $this->view->chart = $array;
        $this->view->month = $month;
        $this->view->year = $year;
        $this->view->id = $id;
        $this->view->plugin_url = trailingslashit(WP_PLUGIN_URL . '/' . dirname(plugin_basename(__FILE__)));
        $this->view->month_name = $this->config['months'];
    }

    public function user_activity_daily_change() {
        global $wpdb, $current_user;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Page Analytics <img src="'.$this->config['imagesUrl'].'pdf.png" style="cursor:pointer;margin-bottom: -8px;width: 24px;float:right;margin-right:10px;" onclick="make_pdf();" /><img src="'.$this->config['imagesUrl'].'excel.png" style="cursor:pointer;margin-bottom: -8px;width: 24px;float:right;margin-right:10px;" onclick="make_excel();" />';
        $this->view->page = $wpdb->get_results("SELECT * FROM st_likepluginfbpagelist WHERE user_id = " . $current_user->ID);
        $id = (isset($_POST['pageid'])) ? $_POST['pageid'] : $wpdb->get_var("SELECT pageid FROM st_likepluginfbpagelist WHERE user_id=" . $current_user->ID);
        $month = (isset($_POST['month'])) ? $_POST['month'] : date('m');
        $year = (isset($_POST['year'])) ? $_POST['year'] : date('Y');
        $timestamp = mktime(0, 0, 0, $month, 1, $year);
        $dates = date(t, $timestamp);
        $b_likes = 0;
        $b_shares = 0;
        $b_comments = 0;
        $b_posts = 0;
        $b_users = 0;
        $check = 0;
        $b_fancount = 0;
        for ($i = 1; $i <= $dates; $i++) {
            $day = ($i < 10) ? '0' . $i : $i;
            $array_date[] = '"' . $day . '-' . $month . '-' . $year . '"';
        }
        $check2 = '"01-'.$month.'-'.$year.'"';
        if(in_array($check2,$array_date)){
            if($month == '01'){
                $month2 = '12';
                $year2 = $year-1;
            }
            else{
                $month2 = $month-1;
                $year2 = $year;
            }
            $time2 = mktime(0, 0, 0, $month2, 1, $year2);
            $dates2 = date(t,$time2);
            $result2 = $wpdb->get_row("SELECT * FROM st_likepluginfbpagestatistics WHERE facebookpageid=" . $id . " AND date = '$dates2-$month2-$year2'");
            $b_likes = $result2->numberoflikes;
            $b_shares = $result2->numberofshares;
            $b_comments = $result2->numberofcomments;
            $b_posts = $result2->numberofposts;
            $b_users = $result2->numberofusers;
            $b_fancount = $result2->fancount; 
        }
        $where = implode(",", $array_date);
        $where2 = ' AND numberofusers > 0';
        $start = $wpdb->get_row("SELECT * FROM st_likepluginfbpagestatistics WHERE facebookpageid=" . $id  . $where2 . "  ORDER BY statiisticsid LIMIT 0,1");
        $end = $wpdb->get_row("SELECT * FROM st_likepluginfbpagestatistics WHERE facebookpageid=" . $id . " AND date IN (" . $where . ")" . $where2 . "  ORDER BY date DESC LIMIT 0,1");
        $myrows = $wpdb->get_results("SELECT * FROM st_likepluginfbpagestatistics WHERE facebookpageid=" . $id . " AND date IN (" . $where . ")");
        foreach ($myrows as $result) {
            $row = $wpdb->get_row("SELECT * FROM st_likepluginfbpagelist WHERE pageid=" . $result->facebookpageid);
            $data = array();
            if ($result->date != $start->date) {
                $data['likes'] = $result->numberoflikes - $b_likes;
                $data['shares'] = $result->numberofshares - $b_shares;
                $data['comments'] = $result->numberofcomments - $b_comments;
                $data['posts'] = $result->numberofposts - $b_posts;
                $data['users'] = $result->numberofusers - $b_users;
                $data['fancount'] = $result->fancount - $b_fancount;
                $data['day'] = $result->date;
                $array[] = $data;
            }
            $b_likes = $result->numberoflikes;
            $b_shares = $result->numberofshares;
            $b_comments = $result->numberofcomments;
            $b_posts = $result->numberofposts;
            $b_users = $result->numberofusers;
            $b_fancount = $result->fancount;
        }
        $this->view->chart = $array;
        $this->view->month = $month;
        $this->view->year = $year;
        $this->view->id = $id;
        $this->view->plugin_url = trailingslashit(WP_PLUGIN_URL . '/' . dirname(plugin_basename(__FILE__)));
        $this->view->month_name = $this->config['months'];
    }

    public function viral_spread() {
        global $wpdb, $current_user;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Page Analytics <img src="'.$this->config['imagesUrl'].'pdf.png" style="cursor:pointer;margin-bottom: -8px;width: 24px;float:right;margin-right:10px;" onclick="make_pdf();" /><img src="'.$this->config['imagesUrl'].'excel.png" style="cursor:pointer;margin-bottom: -8px;width: 24px;float:right;margin-right:10px;" onclick="make_excel();" />';
        $this->view->page = $wpdb->get_results("SELECT * FROM st_likepluginfbpagelist WHERE user_id = " . $current_user->ID);
        $id = (isset($_POST['pageid'])) ? $_POST['pageid'] : $wpdb->get_var("SELECT pageid FROM st_likepluginfbpagelist WHERE user_id=" . $current_user->ID);
        $month = (isset($_POST['month'])) ? $_POST['month'] : date('m');
        $year = (isset($_POST['year'])) ? $_POST['year'] : date('Y');
        $timestamp = mktime(0, 0, 0, $month, 1, $year);
        $dates = date(t, $timestamp);
        $b_likes = 0;
        $b_shares = 0;
        $b_comments = 0;
        $b_posts = 0;
        $b_users = 0;
        $check = 0;
        $b_fancount = 0;
        for ($i = 1; $i <= $dates; $i++) {
            $day = ($i < 10) ? '0' . $i : $i;
            $array_date[] = '"' . $day . '-' . $month . '-' . $year . '"';
        }
        $where = implode(",", $array_date);
        $where2 = ' AND numberofposts > 0 AND numberofcomments > 0 AND numberoflikes > 0 AND numberofshares > 0 ';
        $start = $wpdb->get_row("SELECT * FROM st_likepluginfbpagestatistics WHERE facebookpageid=" . $id . " AND date IN (" . $where . ")" . $where2 . "  ORDER BY date LIMIT 0,1");
        $end = $wpdb->get_row("SELECT * FROM st_likepluginfbpagestatistics WHERE facebookpageid=" . $id . " AND date IN (" . $where . ")" . $where2 . "  ORDER BY date DESC LIMIT 0,1");
        $myrows = $wpdb->get_results("SELECT * FROM st_likepluginfbpagestatistics WHERE facebookpageid=" . $id . " AND date IN (" . $where . ")");
        foreach ($myrows as $result) {
            $row = $wpdb->get_row("SELECT * FROM st_likepluginfbpagelist WHERE pageid=" . $result->facebookpageid);

            $data['likes'] = $result->numberoflikes;
            $data['shares'] = $result->numberofshares;
            $data['comments'] = $result->numberofcomments;
            $data['posts'] = $result->numberofposts;
            $data['users'] = $result->numberofusers;
            $data['fancount'] = $result->fancount;
            $data['day'] = $result->date;
            $array[] = $data;
        }
        $this->view->chart = $array;
        $this->view->month = $month;
        $this->view->year = $year;
        $this->view->id = $id;
        $this->view->plugin_url = trailingslashit(WP_PLUGIN_URL . '/' . dirname(plugin_basename(__FILE__)));
        $this->view->month_name = $this->config['months'];
    }

    public function viral_spread_daily_change() {
        global $wpdb, $current_user;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Page Analytics <img src="'.$this->config['imagesUrl'].'pdf.png" style="cursor:pointer;margin-bottom: -8px;width: 24px;float:right;margin-right:10px;" onclick="make_pdf();" /><img src="'.$this->config['imagesUrl'].'excel.png" style="cursor:pointer;margin-bottom: -8px;width: 24px;float:right;margin-right:10px;" onclick="make_excel();" />';
        $this->view->page = $wpdb->get_results("SELECT * FROM st_likepluginfbpagelist WHERE user_id = " . $current_user->ID);
        $id = (isset($_POST['pageid'])) ? $_POST['pageid'] : $wpdb->get_var("SELECT pageid FROM st_likepluginfbpagelist WHERE user_id=" . $current_user->ID);
        $month = (isset($_POST['month'])) ? $_POST['month'] : date('m');
        $year = (isset($_POST['year'])) ? $_POST['year'] : date('Y');
        $timestamp = mktime(0, 0, 0, $month, 1, $year);
        $dates = date(t, $timestamp);
        $b_likes = 0;
        $b_shares = 0;
        $b_comments = 0;
        $b_posts = 0;
        $b_users = 0;
        $check = 0;
        $b_fancount = 0;
        for ($i = 1; $i <= $dates; $i++) {
            $day = ($i < 10) ? '0' . $i : $i;
            $array_date[] = '"' . $day . '-' . $month . '-' . $year . '"';
        }
        $check2 = '"01-'.$month.'-'.$year.'"';
        if(in_array($check2,$array_date)){
            if($month == '01'){
                $month2 = '12';
                $year2 = $year-1;
            }
            else{
                $month2 = $month-1;
                $year2 = $year;
            }
            $time2 = mktime(0, 0, 0, $month2, 1, $year2);
            $dates2 = date(t,$time2);
            $result2 = $wpdb->get_row("SELECT * FROM st_likepluginfbpagestatistics WHERE facebookpageid=" . $id . " AND date = '$dates2-$month2-$year2'");
            $b_likes = $result2->numberoflikes;
            $b_shares = $result2->numberofshares;
            $b_comments = $result2->numberofcomments;
            $b_posts = $result2->numberofposts;
            $b_users = $result2->numberofusers;
            $b_fancount = $result2->fancount; 
        }
        $where = implode(",", $array_date);
        $where2 = ' AND numberofposts > 0 AND numberofcomments > 0 AND numberoflikes > 0 AND numberofshares > 0 ';
        $start = $wpdb->get_row("SELECT * FROM st_likepluginfbpagestatistics WHERE facebookpageid=" . $id  . $where2 . "  ORDER BY statiisticsid LIMIT 0,1");
        $end = $wpdb->get_row("SELECT * FROM st_likepluginfbpagestatistics WHERE facebookpageid=" . $id . " AND date IN (" . $where . ")" . $where2 . "  ORDER BY date DESC LIMIT 0,1");
        $myrows = $wpdb->get_results("SELECT * FROM st_likepluginfbpagestatistics WHERE facebookpageid=" . $id . " AND date IN (" . $where . ")");
        foreach ($myrows as $result) {
            $row = $wpdb->get_row("SELECT * FROM st_likepluginfbpagelist WHERE pageid=" . $result->facebookpageid);
            $data = array();
            if ($result->date != $start->date) {
                $data['likes'] = $result->numberoflikes - $b_likes;
                $data['shares'] = $result->numberofshares - $b_shares;
                $data['comments'] = $result->numberofcomments - $b_comments;
                $data['posts'] = $result->numberofposts - $b_posts;
                $data['users'] = $result->numberofusers - $b_users;
                $data['fancount'] = $result->fancount - $b_fancount;
                $data['day'] = $result->date;
                $array[] = $data;
            }
            $b_likes = $result->numberoflikes;
            $b_shares = $result->numberofshares;
            $b_comments = $result->numberofcomments;
            $b_posts = $result->numberofposts;
            $b_users = $result->numberofusers;
            $b_fancount = $result->fancount;
        }
        $this->view->chart = $array;
        $this->view->month = $month;
        $this->view->year = $year;
        $this->view->id = $id;
        $this->view->plugin_url = trailingslashit(WP_PLUGIN_URL . '/' . dirname(plugin_basename(__FILE__)));
        $this->view->month_name = $this->config['months'];
    }

    public function page_to_tab() {
        global $wpdb;
        $options = $this->option;
        $this->view->headIcon = 'icon_re';
        $this->view->option = $options['facebook_tab'];
        $this->view->page = $wpdb->get_results("SELECT * FROM wp_posts WHERE post_type='page' AND post_status='publish'");
        $this->view->headTitle1 = 'Facebook tab';
        if (isset($_POST['data'])) {
            extract($_POST['data']);
            if (isset($page)) {
                $option['page'] = '1';
            } else {
                $option['page'] = '0';
            }
            if (isset($author)) {
                $option['author'] = "1";
            } else {
                $options['author'] = "0";
            }
            $option['id'] = $id;
            $option['by'] = $by;
            $option['pageid'] = $pageid;
            $options['facebook_tab'] = $option;
            $this->updateOption($options);
            //update_option('facebook_tab',$option);
            $arg = array(
                'status' => 'success',
                'message' => __('Edit successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));

            die;
        }
    }

    public function facebook_search() {
        global $wpdb, $current_user;
        $this->view->plugin_url = trailingslashit(WP_PLUGIN_URL . '/' . dirname(plugin_basename(__FILE__)));
        $stFacebookToolbox_model = $this->loadmodel("stFacebookSearch");
        if ($_REQUEST['short_action'] == 'delete') {

            $wpdb->query("DELETE FROM st_likepluginsearchterms WHERE searchtermid = " . $_POST['id'] . " AND user_id = " . $current_user->ID);
            $arg = array(
                'status' => 'success',
                'message' => __('Delete successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));
        }
        $args = array();
        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;
        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 0;
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 0;
        if ($_REQUEST['sort']) {
            $args['order'] = array($sort, $sort_type);
        }
        $args['limit'] = array($start, $limit);
        $args['where'] = ' user_id=' . $current_user->ID;
        $results = $stFacebookToolbox_model->getRecords($args);
        $total = $stFacebookToolbox_model->countRecords();
        $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName);
        $columns = array(
            'searchtermid' => __('ID', $this->config['plugin_name']),
            'searchterm' => __('Search term', $this->config['plugin_name']),
        );
        register_column_headers('stFacebookToolbox_stFacebookToolbox', $columns);
        $this->view->results = $results;
        $this->view->pagination = $pagination;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Facebook search';
        $this->view->iconNew = 'Add New Search Term';
        $this->view->iconAction = "loadPage('add_facebook_search')";
    }

    public function add_facebook_search() {
        global $wpdb, $current_user;
        $stFacebookToolbox_model = $this->loadmodel("stFacebookSearch");

        //initialize variable to view
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Add Facebook search';
        $this->view->button = 'Add';
        $this->view->user_id = $current_user->ID;
        if (isset($_POST['id'])) {
            $this->view->headTitle1 = 'Edit Facebook search';
            $this->view->button = 'Edit';
            $this->view->id = $_POST['id'];
            $this->view->searchterm = $wpdb->get_var("SELECT searchterm FROM st_likepluginsearchterms WHERE searchtermid=" . $_POST['id'] . " AND user_id = " . $current_user->ID);
        }
        // Handle post
        if ($_POST['data']) {
            extract($_POST['data']);
            if (!isset($id)) {
                $wpdb->insert('st_likepluginsearchterms', $_POST['data']);
            } else {
                $wpdb->update('st_likepluginsearchterms', array('searchterm' => $searchterm, 'user_id' => $current_user->ID), array('searchtermid' => $id));
            }
        }
    }

    public function update_search() {
        global $wpdb;
        require_once $this->config['classDir'] . 'facebook/facebook.php';
        $stFacebookToolbox_model = $this->loadmodel("stFacebookSearch");
        $stFacebookToolbox_model->update_search($_POST['search']);
        die;
    }

    public function site_map() {
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Site map manager';
        global $wpdb, $current_user;
        $stFacebookToolbox_model = $this->loadmodel("stSiteMap");

        // short action handle
        if ($_REQUEST['short_action'] == 'delete') {

            $wpdb->query("DELETE FROM st_sitemap WHERE id = " . $_POST['id'] . " AND user_id = " . $current_user->ID);
            $wpdb->query("DELETE FROM st_likepluginstatistics WHERE site_id = " . $_POST['id'] . " AND user_id = " . $current_user->ID);
            $wpdb->query("DELETE FROM st_sitemap_link WHERE site_id = " . $_POST['id'] . " AND user_id = " . $current_user->ID);
            $arg = array(
                'status' => 'success',
                'message' => __('Delete successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));
        }

        $args = array();
        $args['where'] = ' id != "" AND user_id = ' . $current_user->ID;
        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;

        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 0;
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 0;
        if ($_REQUEST['sort']) {
            $args['order'] = array($sort, $sort_type);
        }
        $args['limit'] = array($start, $limit);

        $results = $stFacebookToolbox_model->getRecords($args);
        $total = $stFacebookToolbox_model->countRecords();
        $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName);

        $columns = array(
            'id' => __('SiteID', $this->config['plugin_name']),
            'site_name' => __('Site Name', $this->config['plugin_name']),
            'site_url' => __('Site Map URL', $this->config['plugin_name']),
            'number' => __('URL’s in Site Map', $this->config['plugin_name']),
        );
        register_column_headers('stFacebookToolbox_stFacebookToolbox', $columns);

        //initialize variable to view
        $this->view->results = $results;
        $this->view->pagination = $pagination;
        $this->view->iconNew = 'Add New Site Map';
        $this->view->user_id = $current_user->ID;
        $this->view->iconAction = "loadPage('add_site_map')";
    }

    function add_site_map() {
        global $wpdb, $current_user;
        $stFacebookToolbox_model = $this->loadmodel("stSiteMap");

        //initialize variable to view
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Add Site Map';
        $this->view->user_id = $current_user->ID;
        if (isset($_POST['data'])) {
            $wpdb->insert('st_sitemap', $_POST['data']);
        }
    }

    public function edit_site_map() {
        global $wpdb, $current_user;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Edit Site map';
        $this->view->user_id = $current_user->ID;
        $this->view->id = $_POST['id'];
        $this->view->row = $row = $wpdb->get_row("SELECT * FROM st_sitemap WHERE id=" . $_POST['id']);
        if (isset($_POST['data'])) {
            $wpdb->update('st_sitemap', $_POST['data'], array('id' => $_POST['id'], 'user_id' => $current_user->ID));
        }
    }

    public function update_site_map() {
        global $wpdb;
        $result = $wpdb->get_results("SELECT * FROM st_sitemap WHERE user_id = " . $_POST['id']);
        foreach ($result as $row) {
            $wpdb->query("DELETE FROM st_sitemap_link WHERE user_id=" . $_POST['id'] . " AND site_id =" . $row->id);
            if (substr($row->site_url, -4) == '.xml') {
                $xml = file_get_contents($row->site_url);
                preg_match_all("/<loc>(.*?)<\/loc>/i", $xml, $array);
                $stt = 0;
                foreach ($array[1] as $name) {
                    $wpdb->insert('st_sitemap_link', array('link' => $name, 'user_id' => $_POST['id'], 'site_id' => $row->id));
                    $stt++;
                }
                $wpdb->update('st_sitemap', array('number' => $stt), array('id' => $row->id));
            } else {
                $link = file_get_contents($row->site_url);
                $array = explode("\n", $link);
                $stt = 0;
                foreach ($array as $name) {
                    if ($name != '') {
                        $wpdb->insert('st_sitemap_link', array('link' => $name, 'user_id' => $_POST['id'], 'site_id' => $row->id));
                        $stt++;
                    }
                }
                $wpdb->update('st_sitemap', array('number' => $stt), array('id' => $row->id));
            }
        }
    }

    public function feed_to_tab() {
        $options = $this->option;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Feed to tab';
        $this->view->plugin_url = trailingslashit(WP_PLUGIN_URL . '/' . dirname(plugin_basename(__FILE__)));
        $this->view->option = $option = $options['facebook_feed'];
        if (isset($_POST['data'])) {
            extract($_POST['data']);
            if (isset($date)) {
                $option['date'] = '1';
            } else {
                $option['date'] = '0';
            }
            if (isset($author)) {
                $option['author'] = "1";
            } else {
                $options['author'] = "0";
            }
            if (isset($excerpt)) {
                $option['excerpt'] = "1";
            } else {
                $option['excerpt'] = "0";
            }
            if (isset($images)) {
                $option['images'] = "1";
            } else {
                $option['images'] = "0";
            }
            $option['language'] = $language;
            $option['number'] = $number;
            $option['by'] = $by;
            $options['facebook_feed'] = $option;
            //update_option('facebook_feed',$option);
            $this->updateOption($options);
            $arg = array(
                'status' => 'success',
                'message' => __('Save successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));

            die;
        }
    }

    public function feed_categories() {
        $options = $this->option;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Feed to tab';
        $this->view->option = $options['facebook_feed_category'];
        if (isset($_POST['data'])) {
            $args = array(
                'type' => 'post',
                'hide_empty' => 0
            );
            $categories = get_categories($args);
            foreach ($categories as $category):
                if (isset($_POST['data'][$category->cat_ID])) {
                    $option[$category->cat_ID] = "1";
                } else {
                    $option[$category->cat_ID] = "0";
                }
            endforeach;
            $options['facebook_feed_category'] = $option;
            $this->updateOption($options);
            $arg = array(
                'status' => 'success',
                'message' => __('Updated successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));

            die;
        }
    }

    public function feed_statistics() {
        $stFacebookToolbox_model = $this->loadmodel("stFacebookFeed");

        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Feed to tab';
        $args = array();
        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;
        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 0;
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 0;
        if ($_REQUEST['sort']) {
            $args['order'] = array($sort, $sort_type);
        }
        $args['limit'] = array($start, $limit);
        $results = $stFacebookToolbox_model->getRecords($args);
        $total = $stFacebookToolbox_model->countRecords();
        $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName);
        $columns = array(
            'ids' => __('Post/Page ID', $this->config['plugin_name']),
            'post_id' => __('Post/Page URL', $this->config['plugin_name']),
            'likes' => __('Clicks', $this->config['plugin_name']),
            'ip' => __('Client IP', $this->config['plugin_name']),
            'cdate' => __('Click Date', $this->config['plugin_name'])
        );
        register_column_headers('stFacebookToolbox_stFacebookToolbox', $columns);
        $this->view->results = $results;
        $this->view->pagination = $pagination;
    }

    public function get_fan_list() {
        global $wpdb, $current_user;
        require_once $this->config['classDir'] . 'stfanpage.php';
        if (isset($_POST['type'])) {

            extract($_POST);
            $wpdb->update("st_likepluginfbpagelist", array('get_fan' => json_encode($_POST)), array('pageid' => $pageid));
            $fbObject = new facebookPageAnalytic($cookie);
            if ($type == 0) {
                $data = $fbObject->parseUnder100Fans("", $pageid);
            } else {
                $data = $fbObject->parseUpper100Fans($node_id, $post_form_id, $fb_dtsg, "", false, WP_PLUGIN_DIR . "/stSocialMediaToolbox/tmp/");
            }
            foreach ($data as $k => $u) {
                $u = (array) $u;
                if (count($wpdb->get_results("SELECT * FROM st_fanofpage WHERE fanuserid='" . $u['id'] . "' AND pageid='" . $pageid . "' AND user_id=" . $current_user->ID)) == 0) {
                    $wpdb->insert("st_fanofpage", array('fanuserid' => $u['id'], 'pageid' => $_POST['pageid'], 'user_id' => $current_user->ID));
                }
                $mang[] = $u['id'];
            }
            echo count($mang);
            die;
        }
        $this->view->plugin_url = trailingslashit(WP_PLUGIN_URL . '/' . dirname(plugin_basename(__FILE__)));
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Get Fan List';
        $stFacebookToolbox_model = $this->loadmodel("stFacebookPage");
        $this->view->result = $stFacebookToolbox_model->get_pagelist($current_user->ID);
        if (isset($_POST['pageid'])) {
            $array = json_decode(file_get_contents("http://graph.facebook.com/" . $_POST['pageid']));
            $value = json_decode(stripslashes($wpdb->get_var("SELECT get_fan FROM st_likepluginfbpagelist WHERE pageid=" . $_POST['pageid'])));
            if ($array->likes > 100) {
                $this->view->number = "More than 100 Fans";
                $this->view->page = 1;
                $href = 'http://81.27.40.17/userguides/facebook-toolbox/fbpagefansmorethan100.swf';
                $this->view->over = true;
                $this->view->node_id = $value->node_id;
                $this->view->post_form_id = $value->post_form_id;
                $this->view->fb_dtsg = $value->fb_dtsg;
            } else {
                $this->view->number = "Under 100 Fans";
                $this->view->page = 0;
                $href = 'http://81.27.40.17/userguides/facebook-toolbox/fbpagefans100.swf';
                $this->view->over = false;
            }
            $this->view->alert = "You have <font color='red'>" . $array->likes . "</font> fans. Please fill the extra parameters as below: ( <a href='" . $href . "' id='view_instruction' target='_blank'>View instruction</a> )";
            $this->view->pageid = $_POST['pageid'];
            $this->view->cookie = $value->cookie;
        }
    }

    public function get_facebook_user() {
        global $wpdb, $current_user;
        define('APP_API_KEY', $this->config['facebook_api_key']);
        define('APP_SECRET_KEY', $this->config['facebook_secret']);
        define('APP_ID', $this->config['facebook_app_id']);
        require_once $this->config['classDir'] . 'facebook/facebook.php';
        $facebook = new Facebook(APP_API_KEY, APP_SECRET_KEY, true);
        $result = $wpdb->get_results("SELECT fanuserid FROM st_fanofpage WHERE pageid=" . $_POST['id'] . " AND user_id = " . $current_user->ID . " LIMIT " . $_POST['limit'] . ",500", ARRAY_N);
        foreach ($result as $row) {
            $array[] = $row[0];
        }
        $userInfo = $facebook->api_client->users_getInfo($array, array('uid', 'first_name', 'last_name', 'locale', 'birthday', 'sex', 'current_location', 'profile_url', 'timezone'));
        foreach ($userInfo as $ro) {
            $curent_location = ($ro['current_location']['city'] == '') ? $ro['current_location'] : $ro['current_location']['city'];
            $user_info = array();
            $user_info['birthday'] = $ro['birthday'];
            $user_info['currentlocation'] = $curent_location;
            $user_info['firstname'] = $ro['first_name'];
            $user_info['lastname'] = $ro['last_name'];
            $user_info['locale'] = $ro['locale'];
            $user_info['profileurl'] = $ro['profile_url'];
            $user_info['sex'] = $ro['sex'];
            $user_info['timezone'] = $ro['timezone'];
            $user_info['uid'] = $ro['uid'];
            $user_info['user_id'] = $current_user->ID;
            if (count($wpdb->get_results("SELECT * FROM st_likepluginfbusers WHERE uid=" . $ro['uid'] . " AND user_id = " . $current_user->ID)) > 0) {
                $wpdb->update('st_likepluginfbusers', $user_info, array('uid' => $row['uid']));
            } else {
                $wpdb->insert('st_likepluginfbusers', $user_info);
            }
            if ($wpdb->get_var("SELECT COUNT(*) FROM st_fbuser_relation WHERE system_user_id  = " . $current_user->ID . " AND facebook_user_id = " . $ro['uid']) == 0) {
                $wpdb->insert('st_fbuser_relation', array('system_user_id' => $current_user->ID, 'facebook_user_id' => $ro['uid']));
            }
        }
        echo "success";
        die;
    }

    public function wall_to_wp() {
        $options = $this->option;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Facebook Wall';
        $this->view->option = $options['facebook_wall'];
        if (isset($_POST['data'])) {
            extract($_POST['data']);
            $data['post'] = $post;
            $data['offset'] = $offset;
            $data['id'] = $id;
            $options['facebook_wall'] = $data;
            //update_option('facebook_wall',$data);
            $this->updateOption($options);
            $arg = array(
                'status' => 'success',
                'message' => __('Updated successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));

            die;
        }
    }

    public function cronjob_setup() {
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Cron tab setup';
    }

    public function flag_set_up() {
        global $wpdb, $current_user;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Flag set up';
        $this->view->iconNew = 'Add New Flag';
        $this->view->iconAction = "loadPage('add_flag')";
        if ($_REQUEST['short_action'] == 'delete') {

            $wpdb->query("DELETE FROM fbt_flagtypes WHERE flagtypeid = " . $_POST['id'] . " AND user_id = " . $current_user->ID);
            $arg = array(
                'status' => 'success',
                'message' => __('Delete successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));
        }
        $stFacebookToolbox_model = $this->loadmodel("stFacebookFlag");
        $args = array();
        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;
        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 0;
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 0;
        if ($_REQUEST['sort']) {
            $args['order'] = array($sort, $sort_type);
        }
        $args['where'] = ' user_id = ' . $current_user->ID;
        $args['limit'] = array($start, $limit);
        $results = $stFacebookToolbox_model->getRecords($args);
        $total = $stFacebookToolbox_model->countRecords();
        $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName);
        $columns = array(
            'flagname' => __('Flag name', $this->config['plugin_name']),
            'flagcolorcode' => __('Color code', $this->config['plugin_name']),
            'flagdescription' => __('Flag Description', $this->config['plugin_name']),
        );
        register_column_headers('stFacebookToolbox_stFacebookToolbox', $columns);
        $this->view->results = $results;
        $this->view->pagination = $pagination;
    }

    public function add_flag() {
        global $wpdb, $current_user;
        $this->view->user_id = $current_user->ID;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Add flag';
        if (isset($_POST['data'])) {
            $wpdb->insert('fbt_flagtypes', $_POST['data']);
            $arg = array(
                'status' => 'success',
                'message' => __('Save successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));
            die;
        }
    }

    public function edit_flag() {
        global $wpdb, $current_user;
        $this->view->result = $wpdb->get_row("SELECT * FROM fbt_flagtypes WHERE flagtypeid=" . $_POST['id'] . " AND user_id = " . $current_user->ID);
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'General settings';
        if (isset($_POST['data'])) {
            $wpdb->update('fbt_flagtypes', $_POST['data'], array('flagtypeid' => $_GET['id']));
            $arg = array(
                'status' => 'success',
                'message' => __('Save successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));

            die;
        }
    }

    public function user_analytics() {
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'User Analytics';
    }

    public function user_list() {
        global $wpdb, $current_user;
        define('APP_API_KEY', $this->config['facebook_api_key']);
        define('APP_SECRET_KEY', $this->config['facebook_secret']);
        define('APP_ID', $this->config['facebook_app_id']);
        require_once $this->config['classDir'] . 'facebook/facebook.php';
        $facebook = new Facebook(APP_API_KEY, APP_SECRET_KEY, true);
        $stFacebookToolbox_model = $this->loadmodel("stFacebookUser");
        if ($_POST['search'] == '1') {

            //$result = $wpdb->get_results("SELECT * FROM st_likepluginfbusers WHERE user_id = ".$current_user->ID. " AND ((firstname = '' AND lastname='') OR pic_small = '') ORDER BY firstname ASC");
            //echo "SELECT * FROM st_likepluginfbusers WHERE  user_id = ".$current_user->ID;
            //die;
            $result = $wpdb->get_results("SELECT * FROM st_likepluginfbusers WHERE  user_id = " . $current_user->ID . " AND ((firstname = '' AND lastname='') OR pic_small = '') ORDER BY firstname ASC");
            foreach ($result as $row) {
                $user_id[] = $row->uid;
            }
            $user_id = implode(',', $user_id);

            //$pageInfo = $facebook->api_client->pages_getInfo($row->uid,'page_id,name,pic_square,type,website',$row->uid,'');
            $user_facebook = $facebook->api_client->fql_query('SELECT first_name,birthday,current_location,last_name,locale,profile_url,pic_small,sex,timezone,uid FROM user WHERE uid IN (' . $user_id . ')');
            foreach ($user_facebook as $ro) {
                $user_info = array();
                $user_info['birthday'] = $ro['birthday'];
                $user_info['currentlocation'] = $ro['current_location'];
                $user_info['firstname'] = $ro['first_name'];
                $user_info['lastname'] = $ro['last_name'];
                $user_info['locale'] = $ro['locale'];
                $user_info['pic_small'] = $ro['pic_small'];
                $user_info['profileurl'] = $ro['profile_url'];
                $user_info['sex'] = $ro['sex'];
                $user_info['timezone'] = $ro['timezone'];
                $user_info['uid'] = $ro['uid'];
                $user_info['user_id'] = $current_user->ID;
                $wpdb->update('st_likepluginfbusers', $user_info, array('uid' => $ro['uid']));
            }
            $pageInfo = $facebook->api_client->fql_query('SELECT page_id,name,pic_small,website FROM page WHERE page_id IN (' . $user_id . ')');
            foreach ($pageInfo as $ro) {
                $user_info = array();
                $user_info['currentlocation'] = $ro['website'];
                $user_info['firstname'] = $ro['name'];
                $user_info['pic_small'] = $ro['pic_small'];
                $user_info['user_id'] = $current_user->ID;
                $wpdb->update('st_likepluginfbusers', $user_info, array('uid' => $ro['page_id']));
            }
            $appInfo = $facebook->api_client->fql_query('SELECT app_id,display_name,logo_url,company_name FROM application WHERE app_id IN (' . $user_id . ')');
            foreach ($appInfo as $ro) {
                $user_info = array();
                $user_info['currentlocation'] = $ro['company_name'];
                $user_info['firstname'] = $ro['display_name'];
                $user_info['pic_small'] = $ro['logo_url'];
                $user_info['user_id'] = $current_user->ID;
                $wpdb->update('st_likepluginfbusers', $user_info, array('uid' => $ro['app_id']));
            }





            die;
        }
        if ($_REQUEST['short_action'] == 'delete') {

            $wpdb->query("DELETE FROM st_fbuser_relation WHERE facebook_user_id = " . $_POST['id'] . " AND system_user_id = " . $current_user->ID);
            $arg = array(
                'status' => 'success',
                'message' => __('Delete successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));
        }
        $this->view->plugin_url = trailingslashit(WP_PLUGIN_URL . '/' . dirname(plugin_basename(__FILE__)));
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'User Analytics';

        $args = array();
        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;
        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 'firstname';
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 'ASC';
        if ($sort) {
            $args['order'] = array($sort, $sort_type);
        }
        $args['limit'] = array($start, $limit);
        $args['multi_query'] = "SELECT *  FROM st_likepluginfbusers fbu,(SELECT facebook_user_id FROM st_fbuser_relation WHERE system_user_id = {$current_user->ID}) ru WHERE fbu.uid = ru.facebook_user_id";
        $results = $stFacebookToolbox_model->getRecords($args);
        $total = $wpdb->get_var("SELECT COUNT(*)  FROM st_likepluginfbusers fbu,(SELECT facebook_user_id FROM st_fbuser_relation WHERE system_user_id = {$current_user->ID}) ru WHERE fbu.uid = ru.facebook_user_id");
        $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName);
        $columns = array(
            'uid' => __('Profile picture', $this->config['plugin_name']),
            'firstname' => __('First name', $this->config['plugin_name']),
            'lastname' => __('Last name', $this->config['plugin_name']),
            'sex' => __('Sex', $this->config['plugin_name']),
            'locale' => __('Locale', $this->config['plugin_name']),
        );
        register_column_headers('stFacebookToolbox_stFacebookToolbox', $columns);
        $this->view->results = $results;
        $this->view->pagination = $pagination;
    }

    public function search_analytics() {
        global $wpdb, $current_user;
        $this->view->result = $wpdb->get_results("SELECT * FROM st_likepluginsearchterms WHERE user_id = " . $current_user->ID);
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Search Analytics';
        $term = (isset($_POST['term'])) ? $_POST['term'] : 0;
        $month = (isset($_POST['month'])) ? $_POST['month'] : date('m');
        $year = (isset($_POST['year'])) ? $_POST['year'] : date('Y');
        $timestamp = mktime(0, 0, 0, $month, 1, $year);
        $dates = date(t, $timestamp);
        $c = 0;
        $check = 0;
        $b_fancount = 0;
        for ($i = 1; $i <= $dates; $i++) {
            $day = ($i < 10) ? '0' . $i : $i;
            $array_date[] = '"' . $day . '-' . $month . '-' . $year . '"';
        }
        $where = implode(",", $array_date);
        $where2 = '';
        if (intval($term) != 0) {
            $where2 .= " AND searchtermid=" . $term;
        }
        $start = $wpdb->get_row("SELECT date FROM `st_likepluginfbmessages` WHERE  date IN (" . $where . ")  " . $where2 . " AND user_id = " . $current_user->ID . " ORDER BY date LIMIT 0,1");
        $end = $wpdb->get_row("SELECT date FROM `st_likepluginfbmessages` WHERE  date IN (" . $where . ")   " . $where2 . "  AND user_id = " . $current_user->ID . " ORDER BY date DESC LIMIT 0,1");
        for ($i = 1; $i <= $dates; $i++) {
            $day = ($i < 10) ? "0" . $i : $i;
            $date = '"' . $day . '-' . $month . '-' . $year . '"';
            $count = $wpdb->get_var("SELECT COUNT(messageid) FROM `st_likepluginfbmessages` WHERE  date =" . $date . $where2 . " AND user_id = " . $current_user->ID);
            if ($count > 0) {
                $data = array();
                $data['count'] = $count;
                $data['day'] = $date;
                $array[] = $data;
            } else {
                $data = array();
            }
        }
        $this->view->chart = $array;
        $this->view->month = $month;
        $this->view->year = $year;
        $this->view->term = $term;
        $this->view->plugin_url = trailingslashit(WP_PLUGIN_URL . '/' . dirname(plugin_basename(__FILE__)));
        $this->view->month_name = $this->config['months'];
    }

    public function search_analytics_daily_change() {
        global $wpdb, $current_user;
        $this->view->result = $wpdb->get_results("SELECT * FROM st_likepluginsearchterms WHERE user_id = " . $current_user->ID);
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Search Analytics';
        $term = (isset($_POST['term'])) ? $_POST['term'] : 0;
        $month = (isset($_POST['month'])) ? $_POST['month'] : date('m');
        $year = (isset($_POST['year'])) ? $_POST['year'] : date('Y');
        $timestamp = mktime(0, 0, 0, $month, 1, $year);
        $dates = date(t, $timestamp);
        $c = 0;
        $check = 0;
        $b_fancount = 0;
        for ($i = 1; $i <= $dates; $i++) {
            $day = ($i < 10) ? '0' . $i : $i;
            $array_date[] = '"' . $day . '-' . $month . '-' . $year . '"';
        }
        $where = implode(",", $array_date);
        $where2 = '';
        if (intval($term) != 0) {
            $where2 .= " AND searchtermid=" . $term;
        }
        $start = $wpdb->get_row("SELECT date FROM `st_likepluginfbmessages` WHERE  date IN (" . $where . ")  " . $where2 . "  AND user_id = " . $current_user->ID . " ORDER BY date LIMIT 0,1");
        $end = $wpdb->get_row("SELECT date FROM `st_likepluginfbmessages` WHERE  date IN (" . $where . ")   " . $where2 . "  AND user_id = " . $current_user->ID . " ORDER BY date DESC LIMIT 0,1");
        for ($i = 1; $i <= $dates; $i++) {
            $day = ($i < 10) ? "0" . $i : $i;
            $date = '"' . $day . '-' . $month . '-' . $year . '"';
            $count = $wpdb->get_var("SELECT COUNT(messageid) FROM `st_likepluginfbmessages` WHERE  date =" . $date . $where2 . "  AND user_id = " . $current_user->ID);
            if ($count > 0) {
                $data = array();

                $data['count'] = $count - $c;
                $c = $count;
                if (str_replace('"', '', $date) == $start->date) {
                    $data['count'] = 0;
                }
                $data['day'] = $date;
                $array[] = $data;
            } else {
                $data = array();
                $endday = (($i - 1) < 10) ? "0" . ($i - 1) : ($i - 1);
                $endday2 = $endday . '-' . $month . '-' . $year;
                $data['count'] = 0 - $c;
                if ($endday2 == $end->date) {
                    $data['count'] = 0;
                }
                $c = 0;
                $data['day'] = $date;
                $array[] = $data;
            }
        }
        $this->view->chart = $array;
        $this->view->month = $month;
        $this->view->year = $year;
        $this->view->term = $term;
        $this->view->plugin_url = trailingslashit(WP_PLUGIN_URL . '/' . dirname(plugin_basename(__FILE__)));
        $this->view->month_name = $this->config['months'];
    }

    public function search_results() {
        global $wpdb, $current_user;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Search Analytics';
        $stFacebookToolbox_model = $this->loadmodel("stFacebookMessage");
        if ($_POST['delete'] == 'true') {
            $wpdb->query("DELETE FROM `st_likepluginfbmessages` WHERE `messageid` IN (" . stripslashes(str_replace("-", ",", $_POST['id'])) . ") AND user_id = " . $current_user->ID);
            $arg = array(
                'status' => 'success',
                'message' => __('Delete successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));
        }
        if ($_POST['apply_flag'] == 'true') {
            $wpdb->query("UPDATE `st_likepluginfbmessages` SET flagtypeid=" . $_POST['flag_value'] . " WHERE `messageid` IN (" . stripslashes(str_replace("-", ",", $_POST['id'])) . ") AND user_id = " . $current_user->ID);
            $arg = array(
                'status' => 'success',
                'message' => __('Update successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));
        }
        if ($_POST['remove_flag'] == 'true') {
            $wpdb->query("UPDATE `st_likepluginfbmessages` SET flagtypeid=0 WHERE `messageid` IN (" . stripslashes(str_replace("-", ",", $_POST['id'])) . ") AND user_id = " . $current_user->ID);
            $arg = array(
                'status' => 'success',
                'message' => __('Update successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));
        }
        $this->view->dterm = $_POST['term'];
        $this->view->dtype = $_POST['type'];
        $this->view->dflag = $_POST['flag'];
        $args = array();
        $args['where'] = ' user_id = ' . $current_user->ID;
        if (isset($_POST['term']) && intval($_POST['term']) != 0) {
            $args['where'] .= ' AND searchtermid=' . $_POST['term'];
        }
        if (isset($_POST['type']) && $_POST['type'] != '0') {
            $args['where'] .= ' AND messagetypeid="' . $_POST['type'] . '"';
        }
        if (isset($_POST['flag']) && intval($_POST['flag']) != 0) {
            $args['where'] .= ' AND flagtypeid=' . $_POST['flag'];
        }
        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;
        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 0;
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 0;
        if ($_REQUEST['sort']) {
            $args['order'] = array($sort, $sort_type);
        } else {
            $args['order'] = array('likes', 'DESC');
        }
        $args['limit'] = array($start, $limit);
        $results = $stFacebookToolbox_model->getRecords($args);
        $total = $wpdb->get_var("SELECT COUNT(*) FROM st_likepluginfbmessages WHERE " . $args['where']);
        $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName);
        $columns = array(
            'picture' => __('Profile Picture', $this->config['plugin_name']),
            'messagetext' => __('Message Text', $this->config['plugin_name']),
            'fromuserid' => __('User', $this->config['plugin_name']),
            'messagetypeid' => __('Message Type', $this->config['plugin_name']),
            'createdtime' => __('Created date/time', $this->config['plugin_name']),
            'likes' => __('Likes', $this->config['plugin_name']),
            'flagtypeid' => __('<input type="checkbox" id="checkbox_all" onclick="stFacebookToolboxcustom.search_result_check_all(this.checked);">&nbsp;Select(all)', $this->config['plugin_name'])
        );
        register_column_headers('stFacebookToolbox_stFacebookToolbox', $columns);
        $this->view->results = $results;
        $this->view->pagination = $pagination;
        $this->view->model = $stFacebookToolbox_model;
        $this->view->term = $wpdb->get_results("SELECT * FROM st_likepluginsearchterms WHERE user_id = " . $current_user->ID);
        $this->view->type = $wpdb->get_results("SELECT messagetypeid FROM `st_likepluginfbmessages` GROUP BY messagetypeid WHERE user_id = " . $current_user->ID);
        $this->view->flag = $wpdb->get_results("SELECT * FROM fbt_flagtypes WHERE user_id = " . $current_user->ID);
    }

    public function like_analytics() {
        global $wpdb, $current_user;
        $stFacebookToolbox_model = $this->loadmodel("stFacebookLike2");
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Like\'s Analytics';
        $this->view->site_id2 = $_POST['site_id'];
        $this->view->sitemap = $wpdb->get_results("SELECT * FROM st_sitemap WHERE user_id = " . $current_user->ID);
        $args = array();
        if ($_POST['site_id'] != 'all' AND $_POST['site_id'] != '') {
            $where = ' AND site_id = ' . $_POST['site_id'];
        } else {
            $where = '';
        }
        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $args['where'] = ' user_id=' . $current_user->ID . $where;
        $limit = 25;
        $start = ($cur_page - 1) * $limit;
        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 0;
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 0;
        if ($_REQUEST['sort']) {
            $args['order'] = array($sort, $sort_type);
        } else {
            $args['order'] = array('url', 'DESC');
        }
        $args['group_by'] = 'url';
        $args['limit'] = array($start, $limit);
        $results = $stFacebookToolbox_model->getRecords($args);
        $wpdb->get_var("SELECT COUNT(*) FROM  (SELECT * FROM `st_likepluginstatistics` WHERE user_id=$current_user->ID ORDER BY `id` DESC) l  WHERE user_id=" . $current_user->ID . $where);
        $args['limit'] = '';
        $this->view->number_total = $total =  $stFacebookToolbox_model->countRecords($args);
        $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName . '&site_id=' . $_POST['site_id']);
        $columns = array(
            'url' => __('URL', $this->config['plugin_name']),
            'like_count' => __('Likes', $this->config['plugin_name']),
            'share_count' => __('Shares', $this->config['plugin_name']),
            'comment_count' => __('Comments', $this->config['plugin_name']),
            'click_count' => __('Clicks', $this->config['plugin_name']),
            'total_like' => __('Total', $this->config['plugin_name'])
        );
        register_column_headers('stFacebookToolbox_stFacebookToolbox', $columns);
        $this->view->results = $results;
        $this->view->pagination = $pagination;
        //$this->view->total = $wpdb->get_results("SELECT ID FROM wp_posts WHERE post_status='publish'");
        $this->view->total = $wpdb->get_var("SELECT COUNT(id) FROM st_sitemap WHERE user_id = " . $current_user->ID);
        $this->view->site_id = $wpdb->get_results("SELECT id FROM st_sitemap WHERE user_id = " . $current_user->ID);
        $this->view->plugin_url = trailingslashit(WP_PLUGIN_URL . '/' . dirname(plugin_basename(__FILE__)));
        
        if (isset($_POST['start'])) {
            $offset = intval($_POST['start']);
            $result = $wpdb->get_results("SELECT * FROM st_sitemap_link WHERE user_id = " . $current_user->ID . " AND site_id = $offset");
            if(count($result) <= 50){
                $array = array();    
                $link = array();
                foreach ($result as $row) {
                  $array[] = urlencode($row->link);
                  $link[] = "'" . $row->link . "'";
                } 
                $string = implode(",", $array);
                $link2 = implode(",", $link);
                $xml = simplexml_load_file('http://api.facebook.com/restserver.php?method=links.getStats&urls=' . $string, NULL, LIBXML_NOBLANKS);
                 foreach ($xml->link_stat as $x) {
                    if ($x->url != '0') {
                        $check = false;
                        if($wpdb->get_var("SELECT COUNT(id) FROM st_likepluginstatistics WHERE url = '$x->url' AND date = '" . date('d-m-Y') . "' AND user_id = " . $current_user->ID. " AND site_id = $offset") > 0){
                            $check = true;
                        }
                        if ($check) {
                            $value['share_count'] = $x->share_count;
                            $value['like_count'] = $x->like_count;
                            $value['comment_count'] = $x->comment_count;
                            //$value['total_count'] = $x->total_count;
                            $value['click_count'] = $x->click_count;
                            $value['user_id'] = $current_user->ID;
                            $value['site_id'] = $offset;
                            $value['total_like'] = $x->total_count;
                            $value['date'] = date('d-m-Y');
                            $type = array('%d', '%d', '%d', '%d', '%d', '%d', '%d', '%s');
                            $wpdb->update('st_likepluginstatistics', $value, array('url' => $x->url), $type, array('%s'));
                        } elseif ($x->total_count > 0) {
                            $value['share_count'] = $x->share_count;
                            $value['like_count'] = $x->like_count;
                            $value['comment_count'] = $x->comment_count;
                            //$value['total_count'] = $x->total_count;
                            $value['click_count'] = $x->click_count;
                            $value['url'] = $x->url;
                            $value['user_id'] = $current_user->ID;
                            $value['site_id'] = $offset;
                            $value['total_like'] = $x->total_count;
                            $value['date'] = date('d-m-Y');
                            $type = array('%d', '%d', '%d', '%d', '%s', '%d', '%d', '%d', '%s');
                            $wpdb->insert('st_likepluginstatistics', $value, $type);
                        }
                    }
            }
            }
            else {
                $max = count($result);
                $i = 0;
                while($i < $max){
                    $result = $wpdb->get_results("SELECT * FROM st_sitemap_link WHERE user_id = " . $current_user->ID . " AND site_id = $offset LIMIT $i,50");
                $array = array();    
                $link = array();
                foreach ($result as $row) {
                  $array[] = urlencode($row->link);
                  $link[] = "'" . $row->link . "'";
                } 
                $string = implode(",", $array);
                $link2 = implode(",", $link);
                $xml = simplexml_load_file('http://api.facebook.com/restserver.php?method=links.getStats&urls=' . $string, NULL, LIBXML_NOBLANKS);
                     foreach ($xml->link_stat as $x) {
                        if ($x->url != '0') {
                            $check = false;
                            if($wpdb->get_var("SELECT COUNT(id) FROM st_likepluginstatistics WHERE url = '$x->url' AND date = '" . date('d-m-Y') . "' AND user_id = " . $current_user->ID. " AND site_id = $offset") > 0){
                                $check = true;
                            }
                            if ($check) {
                                $value['share_count'] = $x->share_count;
                                $value['like_count'] = $x->like_count;
                                $value['comment_count'] = $x->comment_count;
                                //$value['total_count'] = $x->total_count;
                                $value['click_count'] = $x->click_count;
                                $value['user_id'] = $current_user->ID;
                                $value['site_id'] = $offset;
                                $value['total_like'] = $x->total_count;
                                $value['date'] = date('d-m-Y');
                                $type = array('%d', '%d', '%d', '%d', '%d', '%d', '%d', '%s');
                                $wpdb->update('st_likepluginstatistics', $value, array('url' => $x->url), $type, array('%s'));
                            } elseif ($x->total_count > 0) {
                                $value['share_count'] = $x->share_count;
                                $value['like_count'] = $x->like_count;
                                $value['comment_count'] = $x->comment_count;
                                //$value['total_count'] = $x->total_count;
                                $value['click_count'] = $x->click_count;
                                $value['url'] = $x->url;
                                $value['user_id'] = $current_user->ID;
                                $value['site_id'] = $offset;
                                $value['total_like'] = $x->total_count;
                                $value['date'] = date('d-m-Y');
                                $type = array('%d', '%d', '%d', '%d', '%s', '%d', '%d', '%d', '%s');
                                $wpdb->insert('st_likepluginstatistics', $value, $type);
                            }
                        }
                }
                $i += 50;
                }
                
            }
//            foreach ($result as $row) {
//                $array[] = urlencode($row->link);
//                $link[] = "'" . $row->link . "'";
//            }
//            $string = implode(",", $array);
//            $link2 = implode(",", $link);
//            $sql = $wpdb->get_results("SELECT * FROM st_likepluginstatistics WHERE url IN (" . $link2 . ")  AND date = '" . date('d-m-Y') . "' AND user_id = " . $current_user->ID);
//            if (count($sql) > 0) {
//                foreach ($sql as $url) {
//                    $data[] = $url->url;
//                }
//            } else {
//                $data[] = '1';
//            }
            /* $xml = simplexml_load_file('http://api.facebook.com/restserver.php?method=links.getStats&urls=' . $string, NULL, LIBXML_NOBLANKS);
            foreach ($xml->link_stat as $x) {
                if ($x->url != '0') {
                    $check = false;
                    foreach ($data as $url) {
                        if ($x->url == $url)
                            $check = true;
                    }
                    if ($check) {
                        $value['share_count'] = $x->share_count;
                        $value['like_count'] = $x->like_count;
                        $value['comment_count'] = $x->comment_count;
                        //$value['total_count'] = $x->total_count;
                        $value['click_count'] = $x->click_count;
                        $value['user_id'] = $current_user->ID;
                        $value['site_id'] = $row->site_id;
                        $value['total_like'] = $row->total_count;
                        $value['date'] = date('d-m-Y');
                        $type = array('%d', '%d', '%d', '%d', '%d', '%d', '%d', '%s');
                        $wpdb->update('st_likepluginstatistics', $value, array('url' => $x->url), $type, array('%s'));
                    } elseif ($x->total_count > 0) {
                        $value['share_count'] = $x->share_count;
                        $value['like_count'] = $x->like_count;
                        $value['comment_count'] = $x->comment_count;
                        //$value['total_count'] = $x->total_count;
                        $value['click_count'] = $x->click_count;
                        $value['url'] = $x->url;
                        $value['user_id'] = $current_user->ID;
                        $value['site_id'] = $row->site_id;
                        $value['total_like'] = $row->total_count;
                        $value['date'] = date('d-m-Y');
                        $type = array('%d', '%d', '%d', '%d', '%s', '%d', '%d', '%d', '%s');
                        $wpdb->insert('st_likepluginstatistics', $value, $type);
                    }
                }
            }
            $array = array();
            $link = array();
            $data = array();
            $wpdb->query("DELETE FROM st_likepluginstatistics WHERE url = '0'");
            * 
            */
        }
    }

    public function like_daily_change() {
        global $wpdb, $current_user;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Like\'s Analytics';
        $this->view->site_id = $_POST['site_id'];
        $this->view->sitemap = $wpdb->get_results("SELECT * FROM st_sitemap WHERE user_id = " . $current_user->ID);
        $this->view->plugin_url = trailingslashit(WP_PLUGIN_URL . '/' . dirname(plugin_basename(__FILE__)));
        if (isset($_POST['month'])) {
            $month = $_POST['month'];
            $year = $_POST['year'];
            $timestamp = mktime(0, 0, 0, $month, 1, $year);
            $dates = date(t, $timestamp);
            $b_likes = 0;
            $b_shares = 0;
            $b_comments = 0;
            $b_clicks = 0;
            for ($i = 1; $i <= $dates; $i++) {
                $day = ($i < 10) ? '0' . $i : $i;
                $array_date[] = '"' . $day . '-' . $month . '-' . $year . '"';
            }
            $where = implode(",", $array_date);
            if ($_POST['site_id'] != 'all' AND $_POST['site_id'] != '') {
                $site_where = ' AND site_id = ' . $_POST['site_id'];
            } else {
                $site_where = '';
            }
            $myrows = $wpdb->get_results("SELECT SUM(`share_count`) AS share_count,SUM(`like_count`) AS like_count,SUM(`comment_count`) AS comment_count,SUM(`click_count`) AS click_count,date FROM st_likepluginstatistics WHERE date IN (" . $where . ") AND user_id=" . $current_user->ID . $site_where . " GROUP BY date");
            $start = $wpdb->get_row("SELECT date FROM `st_likepluginstatistics` WHERE  date IN (" . $where . ")  AND (`likes`  <> 0 OR `shares`  <> 0 OR `comments`  <> 0 OR `clicks`  <> 0) AND user_id=" . $current_user->ID . $site_where . "  ORDER BY date LIMIT 0,1");
            $end = $wpdb->get_row("SELECT date FROM `st_likepluginstatistics` WHERE  date IN (" . $where . ")  AND (`likes`  <> 0 OR `shares`  <> 0 OR `comments`  <> 0 OR `clicks`  <> 0) AND user_id=" . $current_user->ID . $site_where . "  ORDER BY date DESC LIMIT 0,1");
            foreach ($myrows as $row) {

                $data = array();
                $day = explode("-", $row->date);
                $day = $day[0];

                if ($row->date != $start->date && $row->date != $end->date) {
                    $data['likes'] = intval($row->like_count) - $b_likes;
                    $data['shares'] = intval($row->share_count) - $b_shares;
                    $data['comments'] = intval($row->comment_count) - $b_comments;
                    $data['clicks'] = intval($row->click_count) - $b_clicks;
                    $data['day'] = $row->date;
                    $array[] = $data;
                }
                $b_likes = intval($row->like_count);
                $b_shares = intval($row->share_count);
                $b_comments = intval($row->comment_count);
                $b_clicks = intval($row->click_count);
            }
            $this->view->chart = $array;
            $this->view->month = $month;
            $this->view->year = $year;
            $this->view->month_name = $this->config['months'];
        }
    }

    public function like_aggregated() {
        global $wpdb, $current_user;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Like\'s Analytics';
        $this->view->site_id = $_POST['site_id'];
        $this->view->sitemap = $wpdb->get_results("SELECT * FROM st_sitemap WHERE user_id = " . $current_user->ID);
        $this->view->plugin_url = trailingslashit(WP_PLUGIN_URL . '/' . dirname(plugin_basename(__FILE__)));
        if (isset($_POST['month'])) {
            $month = $_POST['month'];
            $year = $_POST['year'];
            $timestamp = mktime(0, 0, 0, $month, 1, $year);
            $dates = date(t, $timestamp);
            $b_likes = 0;
            $b_shares = 0;
            $b_comments = 0;
            $b_clicks = 0;
            for ($i = 1; $i <= $dates; $i++) {
                $day = ($i < 10) ? '0' . $i : $i;
                $array_date[] = '"' . $day . '-' . $month . '-' . $year . '"';
            }
            $where = implode(",", $array_date);
            if ($_POST['site_id'] != 'all' AND $_POST['site_id'] != '') {
                $site_where = ' AND site_id = ' . $_POST['site_id'];
            } else {
                $site_where = '';
            }
            $myrows = $wpdb->get_results("SELECT SUM(`share_count`) AS share_count,SUM(`like_count`) AS like_count,SUM(`comment_count`) AS comment_count,SUM(`click_count`) AS click_count,date FROM st_likepluginstatistics WHERE date IN (" . $where . ") AND user_id=" . $current_user->ID . $site_where . "  GROUP BY date");
            $start = $wpdb->get_row("SELECT date FROM `st_likepluginhistory` WHERE  date IN (" . $where . ")  AND (`likes`  <> 0 OR `shares`  <> 0 OR `comments`  <> 0 OR `clicks`  <> 0) AND user_id=" . $current_user->ID . $site_where . "  ORDER BY date LIMIT 0,1");
            $end = $wpdb->get_row("SELECT date FROM `st_likepluginhistory` WHERE  date IN (" . $where . ")  AND (`likes`  <> 0 OR `shares`  <> 0 OR `comments`  <> 0 OR `clicks`  <> 0) AND user_id=" . $current_user->ID . $site_where . "  ORDER BY date DESC LIMIT 0,1");
            foreach ($myrows as $row) {

                $data = array();
                $day = explode("-", $row->date);
                $day = $day[0];
                $data['likes'] = $row->like_count;
                $data['shares'] = $row->share_count;
                $data['comments'] = $row->comment_count;
                $data['clicks'] = $row->click_count;
                $data['day'] = $row->date;
                $array[] = $data;
            }
            $this->view->chart = $array;
            $this->view->month = $month;
            $this->view->year = $year;
            $this->view->month_name = $this->config['months'];
        }
    }

    public function setting() {
        $option = $this->option;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Like button';
        $this->view->option = $options = $option['facebook_like_setting'];
        if ($_POST['data']) {
            extract($_POST['data']);
            $options['style'] = $style;
            $options['faces'] = $faces;
            $options['width'] = $width;
            $options['height'] = $height;
            $options['font'] = $font;
            $options['colorscheme'] = $colorscheme;
            $options['verb'] = $verb;
            $options['post'] = $post;
            $options['up'] = $up;
            $options['mode'] = $mode;
            $options['permision'] = $permision;
            if (isset($user)) {
                $options['user'] = '1';
            } else {
                $options['user'] = '0';
            }
            if (isset($categories)) {
                $options['categories'] = "true";
            } else {
                $options['categories'] = "false";
            }
            if (isset($pront)) {
                $options['pront'] = "true";
            } else {
                $options['pront'] = "false";
            }

            if (isset($archive)) {
                $options['archive'] = "true";
            } else {
                $options['archive'] = "false";
            }
            $option['facebook_like_setting'] = $options;
            $this->updateOption($option);
            //update_option('facebook_like_setting',$options);
            $arg = array(
                'status' => 'success',
                'message' => __('Edit successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));
            die;
        }
    }

// Wall Contact Form
    public function wall_contact_form() {
        global $wpdb;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Facebook tools';
        $option = $this->option;
        $this->view->option = $option['facebook_wall_contact_setting']; // get option value then show in view
        if ($_POST['data']) {
            extract($_POST['data']);
            $options['receive_email'] = $receive_email;
            $options['subject'] = $subject;
            $options['email_template'] = $email_template;
            $options['active'] = $active;
            //update new values
            $option['facebook_wall_contact_setting'] = $options;
            $this->updateOption($option);
            $arg = array(
                'status' => 'success',
                'message' => __('Edit successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));
            die;
        }
        //$this->view->chart = $array;
    }

    public function open_graph() {
        $option = $this->option;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Default Open Graph Meta Data';
        $this->view->iconNew = 'Test with URL Linter';
        //$this->view->viewNew = 'setting';
        $this->view->option = $options = $option['facebook_graph'];
        $this->view->iconAction = "open_linter();";
        if ($_POST['data']) {
            extract($_POST['data']);
            if (isset($user)) {
                $_POST['data']['user'] = 1;
            } else {
                $_POST['data']['user'] = 0;
            }
            if (isset($location)) {
                $_POST['data']['location'] = 1;
            } else {
                $_POST['data']['location'] = 0;
            }
            if (isset($contact)) {
                $_POST['data']['contact'] = 1;
            } else {
                $_POST['data']['contact'] = 0;
            }
            $option['facebook_graph'] = $_POST['data'];
            // update_option('facebook_graph',$_POST['data']);
            $this->updateOption($option);
            $arg = array(
                'status' => 'success',
                'message' => __('Edit successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));

            die;
        }
    }

    public function draw_panel() {
        $option = $this->option;
        $this->view->options = $option['facebook_graph'];
        if (isset($_GET['post'])) {
            $id = $_GET['post'];
        } else {
            $id = 0;
        }
        $this->view->id = $id;
//		echo $id;
    }

    public function appPostcards() {
        $arg = array(
//            'current_folder' => $this->config['folder_template'],
            'current_action' => $this->actionName,
//            'where'         => " AND card.`featured` = 1"
        );
        $content_view = $this->getAction('appPostcardsView', $arg);
        $this->view->content_view = $content_view;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Postcards';
    }

    public function ajaxPostAction() {
        $save_type = $_POST['type'];
        $post_card = $_POST['post_card'];
        //Uploads
        if ($save_type == 'upload') {
            $clickedID = $_POST['data']; // Acts as the name
            $filename = $_FILES[$clickedID];
            $filename['name'] = preg_replace('/[^a-zA-Z0-9._\-]/', '', $filename['name']);
            $override['test_form'] = false;
            $override['action'] = 'wp_handle_upload';
            $uploaded_file = wp_handle_upload($filename, $override);
            if(substr($filename['name'],-4,4) == '.pdf'){
                echo $uploaded_file['url'] . "|*|" . $uploaded_file['file'];
                die;
            }
            list($width, $height) = getimagesize($uploaded_file['file']);
            if ($_POST['thumbnail_width'] != '' && $width > $_POST['thumbnail_width']) {
                $max_w = $_POST['thumbnail_width'];
                $max_h = round(($max_w * $height) / $width);
                if (isset($uploaded_file['file'])) {
                    $thumbnail = image_resize($uploaded_file['file'], $max_w, $max_h, true, 'thumb');
                    $thumbnail_url = $upload_dir_url . basename($thumbnail);
                }
            } else {
                if ($_POST['thumbnail_height'] != '') {
                    $max_h = $_POST['thumbnail_height'];
                    $max_w = round(($max_h * $width) / $height);
                    if (isset($uploaded_file['file'])) {
                        $thumbnail = image_resize($uploaded_file['file'], $max_w, $max_h, true, 'thumb');
                        $thumbnail_url = $upload_dir_url . basename($thumbnail);
                    }
                }
            }

            if ($post_card) {
                $max_w = 642;
                $max_h = 431;
                if (isset($uploaded_file['file'])) {
                    $thumbnail = $this->functions->image_zoom($uploaded_file['file'], $max_w, $max_h, false, 'large');
                }
            }

            if (!empty($uploaded_file['error'])) {
                echo 'Upload Error: ' . $uploaded_file['error'] . "|*| Upload Error";
                die;
            } else {
                echo $uploaded_file['url'] . "|*|" . $uploaded_file['file'];
                die;
            } // Is the Response
        } elseif ($save_type == 'image_remove') {
            $file = $_POST['file']; // Acts as the name
            $img_name = basename($file);
            $img_name = explode('.', $img_name);
            $img_name = $img_name[0];
            $file_thumb = str_replace($img_name, $img_name . '-thumb', $file);
            $file_large = str_replace($img_name, $img_name . '-large', $file);
            unlink($file);
            if(substr($file,-4,4) != '.pdf'){
            unlink($file_thumb);
            unlink($file_large);
            }
        }
    }

    public function appPostcardsUser() {
        $stPostCardUser_model = $this->loadmodel("stPostcardUser");

        // short action handle
        if ($_REQUEST['short_action'] == 'delete') {

            if ($stPostCardUser_model->deleteRecords($_REQUEST['id'])) {
                $arg = array(
                    'status' => 'success',
                    'message' => __('Delete successful', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg));
            } else {
                $arg = array(
                    'status' => 'error',
                    'message' => __('Delete unsuccessful', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg));
            }
        }
        
        if ($_REQUEST['short_action'] == 'export') {

            if ($stPostCardUser_model->exportCSV()) {
                $arg = array(
                    'status' => 'success',
                    'message' => __('Delete successful', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg));
            } else {
                $arg = array(
                    'status' => 'error',
                    'message' => __('Delete unsuccessful', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg));
            }
            die;
        }

        $args = array();

        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;

        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 0;
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 0;
        if ($_REQUEST['sort']) {
            $args['order'] = array($sort, $sort_type);
        }
        //user.*, table1.id card_id, sum(table1.shared_email) shared_email, sum(table2.shared_fb) shared_fb
        $args['fields'] = array('user.*, table3.created created, sum(table1.shared_email) shared_email, sum(table2.shared_fb) shared_fb, (COALESCE(shared_email,0)+COALESCE(shared_fb,0)) shared ');
        $args['limit'] = array($start, $limit);
        $smt_user_id = $this->functions->getCurrentSmtUserID($this->config);
        $args['where'] = " smt_user_id = $smt_user_id";
        
        $args['group_by'] = 'user.id';
        $results = $stPostCardUser_model->getRecords($args);
        $args['limit'] = array();
        $total = $stPostCardUser_model->countRecords($args);

        $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName);

        $columns = array(
//            'id' => __('ID', $this->config['plugin_name']),
            'name' => __('Name', $this->config['plugin_name']),
//            'user_name' => __('Username', $this->config['plugin_name']),
            'email' => __('Email', $this->config['plugin_name']),
            'created' => __('Created cards', $this->config['plugin_name']),
            'shared' => __('No. Shares', $this->config['plugin_name']),
            'shared_fb' => __('No. Facebook Shares', $this->config['plugin_name']),
            'shared_email' => __('No. Email Shares', $this->config['plugin_name']),
            'cdate' => __('Created date', $this->config['plugin_name'])
        );
        register_column_headers('stFacebookToolbox_appPostCardUser', $columns);

        //initialize variable to view
        $this->view->results = $results;
        $this->view->pagination = $pagination;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'User list';
        $this->view->iconNew = '';
        $this->view->viewNew = '';
    }

    public function appPostcardsUserEdit() {
        $stPostCardUser_model = $this->loadmodel("stPostcardUser");
        $results = '';
        if (isset($_REQUEST['id'])) {
            $id = $_REQUEST['id'];
            $args = array();
            $args['fields'] = array('table3.*, sum(table1.shared_email) shared_email, sum(table2.shared_fb) shared_fb ');
            $smt_user_id = $this->functions->getCurrentSmtUserID($this->config);
            $args['where'] = " user.smt_user_id = $smt_user_id";
            $args['group_by'] = 'table3.id';
            $args['where'] .= " AND user.id = $id";
            $results = $stPostCardUser_model->getRecords($args);
        }
        $result = $results[0];
        //initialize variable to view
        $this->view->result = $result;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'New User';
        $this->view->headTitle2 = 'Edit User';

        // Handle post
        if ($_POST['data']) {
            $_POST['data']['smt_user_id'] = $this->functions->getCurrentSmtUserID($this->config);
            if (empty($_POST['data']['id'])) {
                $message = "Create new";
            } else {
                $message = "Update";
            }
            if ($stPostCardUser_model->saveStPostcardUser($_POST['data'])) {
                $arg = array(
                    'status' => 'success',
                    'message' => __("{$message} user successful", $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg), 'appPostcardsUser');
            } else {
                $arg = array(
                    'status' => 'error',
                    'message' => __("{$message} user unsuccessful", $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg), 'appPostcardsUser');
            }
        }
    }

    public function appPostcardsCategory() {
        $smt_user_id = $this->functions->getCurrentSmtUserID($this->config);
        $stPostcardCategory_model = $this->loadmodel("stPostcardCategory");

        // short action handle
        if ($_REQUEST['short_action'] == 'delete') {

            if ($stPostcardCategory_model->deleteRecords($_REQUEST['id'])) {
                $arg = array(
                    'status' => 'success',
                    'message' => __('Delete successful', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg));
            } else {
                $arg = array(
                    'status' => 'error',
                    'message' => __('Delete unsuccessful', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg));
            }
        }

        $args = array();

        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;

        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 0;
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 0;
        if ($_REQUEST['sort']) {
            $args['order'] = array($sort, $sort_type);
        }
        $args['where'] = " smt_user_id = $smt_user_id";
        $args['limit'] = array($start, $limit);

        $results = $stPostcardCategory_model->getRecords($args);

        $total = $stPostcardCategory_model->countRecords($args);

        $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName);

        $columns = array(
//            'id' => __('ID', $this->config['plugin_name']),
            'title' => __('Title', $this->config['plugin_name']),
            'description' => __('Description', $this->config['plugin_name']),
            'cdate' => __('Created date', $this->config['plugin_name'])
        );
        register_column_headers('stFacebookToolbox_stPostcardCategory', $columns);

        //initialize variable to view
        $this->view->results = $results;
        $this->view->pagination = $pagination;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Categories';
//        $this->view->iconNew = 'Create new category';
//        $this->view->viewNew = 'appPostcardsCategoryEdit';
    }

    public function appPostcardsCategoryEdit() {
        $stPostcardCategory_model = $this->loadmodel("stPostcardCategory");
        $results = '';
        if (isset($_REQUEST['id'])) {
            $id = $_REQUEST['id'];
            $args = array();
            $args['where'] = " `id` = $id";
            $results = $stPostcardCategory_model->getRecords($args);
        }
        $result = $results[0];
        $smt_user_id = $this->functions->getCurrentSmtUserID($this->config);
        //initialize variable to view
        $this->view->result = $result;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'New Cateogry';
        $this->view->headTitle2 = 'Edit Cateogry';
        $this->view->smt_user_id = $smt_user_id;

        // Handle post
        if ($_POST['data']) {
            if ($stPostcardCategory_model->saveStPostcardCategory($_POST['data'])) {
                $arg = array(
                    'status' => 'success',
                    'message' => __('Create successful', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg), 'appPostcardsCategory');
            } else {
                $arg = array(
                    'status' => 'success',
                    'message' => __('Create unsuccessful', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg), 'appPostcardsCategory');
            }
        }
    }

    public function dashboardPostcard() {
        $stPostcardCategory_model = $this->loadmodel("stPostcardCategory");
        $stPostcardCard_model = $this->loadmodel("stPostcardCard");
        $columns = array(
            'card_name' => __('Name', $this->config['plugin_name']),
            'category_title' => __('Category', $this->config['plugin_name']),
            'thumb_url' => __('Postcard front-side', $this->config['plugin_name']),
//            'logo_url' => __('Postcard logo', $this->config['plugin_name']),
            'nr_created' => __('Times used', $this->config['plugin_name']),
            'featured' => __('Featured', $this->config['plugin_name']),
//            'priority' => __('Priority', $this->config['plugin_name']),
            'cdate' => __('Created date', $this->config['plugin_name']),
        );
        $arg = array(
            'current_folder' => $this->config['folder_template'],
            'current_action' => $this->actionName,
            'columns' => $columns,
            'order' => array('nr_created', 'desc')
        );
        $content_view = $this->getAction('appPostcardsView', $arg);
        $smt_user_id = $this->functions->getCurrentSmtUserId($this->config);
        $args = array();
        $args['where'] = " smt_user_id = $smt_user_id";
        $categories = $stPostcardCategory_model->getRecords($args);

        // 1-7-2011
        $total_user = $stPostcardCard_model->getTotalUser();
        $total_card = $stPostcardCard_model->getTotalCards();
        $total_share_email = $stPostcardCard_model->getTotalShare();
        $total_share_fb = $stPostcardCard_model->getTotalShare('facebook');
        /////////////////
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Dashboard';
        $this->view->content_view = $content_view;
        
        $this->view->total_user = $total_user;
        $this->view->total_card = $total_card;
        $this->view->functions = $this->functions;
        $this->view->total_share_email = $total_share_email;
        $this->view->total_share_fb = $total_share_fb;
    }

    public function showUserCard() {
        require_once $this->config['pluginDir'] . 'stPostcardsClass.php';
        $stPostcardsClass = new stPostcardsClass($this->config, $this->option);
        if ($_REQUEST['short_action'] == 'delete') {

            if ($stPostcardsClass->deleteObject($_REQUEST['id'])) {
                $arg = array(
                    'status' => 'success',
                    'message' => __('Delete successful', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg));
            } else {
                $arg = array(
                    'status' => 'error',
                    'message' => __('Delete unsuccessful', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg));
            }
        }
        $stPostcardCard_model = $this->loadmodel("stPostcardCard");
        $stPostcardCategory_model = $this->loadmodel("stPostcardCategory");
        $args = array();

        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
//        echo $cur_page;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;

        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 0;
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 0;
        if ($_REQUEST['sort']) {
            $args['order'] = array($sort, $sort_type);
        } else {
            $args['order'] = array('cdate', 'desc');
        }
        $args['limit'] = array($start, $limit);

        // begin where codition
        
        $current_folder = isset($_POST['folder']) ? $_POST['folder'] : $this->config['folder_generated'];
        $smt_user_id = $this->functions->getCurrentSmtUserId($this->config);
        $args['where'] = " card.smt_user_id = $smt_user_id";
        
        if (!empty($current_folder)) {
            $args['where'] .= " AND card.`folder_name` like('{$current_folder}')";
        }
        $current_category_id = $_REQUEST['category_id'];
        if (!empty($current_category_id)) {
            $args['where'] .= " AND card.`cat_id` = {$_REQUEST['category_id']}";
        }
        
        $user_id = isset($_POST['user_id']) ? $_POST['user_id'] : '';
        if (!empty($user_id)) {
            $args['where'] .= " AND card.`user_id` = $user_id";
        }
        // end where codition        
        
        $table_card_user = $stPostcardCard_model->prefix . 'st_postcard_user';
        $card_share_table = $stPostcardCard_model->prefix . 'st_postcard_share';
        $card_table = $stPostcardCard_model->prefix . 'st_postcard_card';
        $table_card_category = $stPostcardCard_model->prefix . 'st_postcard_category';
        $table_view_table = $stPostcardCard_model->prefix . 'st_postcard_view';
        $table_card_category = $stPostcardCard_model->prefix . 'st_postcard_category';

        $args['fields'] = array('card_user.name customer_name,card.name card_name, card.logo_file logo_url, card.*, table1.shared_email shared_email, table2.shared_fb shared_fb, (COALESCE(table1.shared_email,0) + COALESCE(table2.shared_fb,0)) shared, sum(card_view.number_view) viewed, card_category.title category_title');
        $extra_sql = "
        INNER JOIN $table_card_user card_user on card.user_id = card_user.id
        LEFT JOIN $table_card_category card_category on card_category.id = card.cat_id
        LEFT JOIN $table_view_table card_view on card_view.card_id = card.id
        LEFT JOIN
        (
        SELECT card.id id , sum(share.number_share) shared_email FROM {$card_table} card 
        LEFT JOIN {$card_share_table} share on share.card_id = card.id 
        WHERE `type_share` like('email') GROUP BY card.id
        ) table1 ON table1.id = card.id 
        LEFT JOIN
        (
        SELECT card.id id, sum(share.number_share) shared_fb FROM {$card_table} card 
        LEFT JOIN {$card_share_table} share on share.card_id = card.id 
        WHERE `type_share` like('facebook') GROUP BY card.id
        ) table2 ON table2.id = card.id 
        ";
        $args['group_by'] = 'card.id';

        $objects = $stPostcardCard_model->getRecords($args, $extra_sql);
        $args['limit'] = array();
        $total = $stPostcardCard_model->countRecords($args, $extra_sql);

        $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName);

        $columns = array(
            'card_name' => __('Name', $this->config['plugin_name']),
            'category_title' => __('Category', $this->config['plugin_name']),
            'customer_name' => __('Generated by', $this->config['plugin_name']),
//                'file_name' => __('File name', $this->config['plugin_name']),
            'thumb_url' => __('Front side', $this->config['plugin_name']),
            'back_thumb_url' => __('Back side', $this->config['plugin_name']),
            'viewed' => __('No. Views', $this->config['plugin_name']),
            'shared' => __('No. Shares', $this->config['plugin_name']),
            'shared_fb' => __('No. Facebook Shares', $this->config['plugin_name']),
            'shared_email' => __('No. Email Shares', $this->config['plugin_name']),
//                'photographer' => __('Photographer', $this->config['plugin_name']),
            'cdate' => __('Created <br/> &nbsp;date', $this->config['plugin_name'])
        );

        register_column_headers('stFacebookToolbox_stPostcards', $columns);

        $args = array();
        $args['where'] = " smt_user_id = $smt_user_id";
        $categories = $stPostcardCategory_model->getRecords($args);
        /////////////////
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Postcards';
        $this->view->objects = $objects;
        $this->view->current_folder = $current_folder;
        $this->view->pagination = $pagination;
        $this->view->categories = $categories;
        $this->view->current_category_id = $current_category_id;
        $this->view->cur_page = $cur_page;
        $this->view->current_user_id = $current_user_id;
    }
    
    public function appPostcardsFeatured() {
        $stPostcardCard_model = $this->loadmodel("stPostcardCard");
        
        if ($_REQUEST['short_action'] == 'change_priority') {
            $data = $_POST['data'];
            if ($stPostcardCard_model->updatePriority($data)) {
                $arg = array(
                    'status' => 'success',
                    'message' => __('Updated successful', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg), $this->actionName);
            } else {
                $arg = array(
                    'status' => 'error',
                    'message' => __('Updated unsuccessful', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg), $this->actionName);
            }
            die;
        }
        
        $columns = array(
            'card_name' => __('Name', $this->config['plugin_name']),
            'category_title' => __('Category', $this->config['plugin_name']),
            'thumb_url' => __('Postcard front-side', $this->config['plugin_name']),
            'logo_url' => __('Postcard logo', $this->config['plugin_name']),
            'nr_created' => __('Times used', $this->config['plugin_name']),
            'featured' => __('Featured', $this->config['plugin_name']),
            'priority' => __('Priority', $this->config['plugin_name']),
            'cdate' => __('Created date', $this->config['plugin_name']),
        );
        $arg = array(
            'current_folder' => $this->config['folder_template'],
            'current_action' => $this->actionName,
            'where'         => " AND card.`featured` = 1",
            'columns'       => $columns,
            'order' => array('priority', 'asc')
        );
        $content_view = $this->getAction('appPostcardsView', $arg);
        
        
        $this->view->content_view = $content_view;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Feature postcard';
    }

    public function appPostcardsView($arg = '') {
        require_once $this->config['pluginDir'] . 'stPostcardsClass.php';
        $stPostcardsClass = new stPostcardsClass($this->config, $this->option);
        $stPostcardCard_model = $this->loadmodel("stPostcardCard");
        
        if(!empty($arg['current_action'])){            
            $current_action1 = $arg['current_action'];
        }else{
            $current_action1 = $this->actionName;
        }
        
        if ($_REQUEST['short_action'] == 'delete') {
            $cur_page = isset($_REQUEST['cur_page']) ? $_REQUEST['cur_page'] : 1;
            if ($stPostcardsClass->deleteObject($_REQUEST['id'])) {
                $arg = array(
                    'status' => 'success',
                    'message' => __('Delete successful', $config['plugin_name'])
                );
                $data = array(
                    'cur_page' => $cur_page
                );
                echo $this->functions->sendMessage(json_encode($arg), $current_action1, $data);
                die;
            } else {
                $arg = array(
                    'status' => 'error',
                    'message' => __('Delete unsuccessful', $config['plugin_name'])
                );
                $data = array(
                    'cur_page' => $cur_page
                );
                echo $this->functions->sendMessage(json_encode($arg), $current_action1, $data);
                die;
            }
        }

        if ($_POST['upload_opject'] == 1) {
            $cur_page = isset($_REQUEST['cur_page']) ? $_REQUEST['cur_page'] : 1;
            $data = $_POST['data'];
//            var_dump($data['faces']);die;
            if (is_array($_POST['data']['faces']))
                $data['faces'] = implode('|*|', $_POST['data']['faces']);
            else
                $data['faces'] = '';
            if ($stPostcardsClass->uploadObject($data)) {
                $arg = array(
                    'status' => 'success',
                    'message' => __('Upload successful', $config['plugin_name'])
                );
                $data = array(
                    'cur_page' => $cur_page
                );
                echo $this->functions->sendMessage(json_encode($arg), $current_action1, $data);
                die;
            } else {
                $arg = array(
                    'status' => 'error',
                    'message' => __('Upload unsuccessful', $config['plugin_name'])
                );
                $data = array(
                    'cur_page' => $cur_page
                );
                echo $this->functions->sendMessage(json_encode($arg), $current_action1, $data);
                die;
            }
        }
        // start add 20-7-2011
        if ($_REQUEST['short_action'] == 'set_featured') {
            $data['id'] = $_POST['card_id'];
            $data['featured'] = $_POST['featured'];
            if ($stPostcardCard_model->setFeatured($data)) {
                $arg = array(
                    'status' => 'success',
                    'message' => __('Updated successful', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg));
            } else {
                $arg = array(
                    'status' => 'error',
                    'message' => __('Updated unsuccessful', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg));
            }
            die;
        }
        // end add 20-7-2011
        
        
        $stPostcardCategory_model = $this->loadmodel("stPostcardCategory");
        $args = array();

        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;

        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 0;
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 0;
        if ($_REQUEST['sort']) {
            $args['order'] = array($sort, $sort_type);
        } else {
            if(empty($arg['order'])){
                $args['order'] = array('cdate', 'desc');                
            }
            else{
                $args['order'] = $arg['order'];
            }
        }
        $args['limit'] = array($start, $limit);
        
        // begin where codition
        if(empty($arg['current_folder'])){
            $current_folder = isset($_POST['folder']) ? $_POST['folder'] : $this->config['folder_template'];
        }else{
            $current_folder = $arg['current_folder'];
        }        
        $smt_user_id = $this->functions->getCurrentSmtUserId($this->config);
        $args['where'] = " card.smt_user_id = $smt_user_id";
        
        if (!empty($current_folder)) {
            $args['where'] .= " AND card.`folder_name` like('{$current_folder}')";
        }        
        
        $current_category_id = $_REQUEST['category_id'];
        if (!empty($current_category_id)) {
            $args['where'] .= " AND card.`cat_id` = {$_REQUEST['category_id']}";
        }
        if(!empty($arg['where'])){
            $args['where'] .= $arg['where'];
        }
        // end where codition

        if ($current_folder != $this->config['folder_template']) {
            $table_card_user = $stPostcardCard_model->prefix . 'st_postcard_user';
            $card_share_table = $stPostcardCard_model->prefix . 'st_postcard_share';
            $card_table = $stPostcardCard_model->prefix . 'st_postcard_card';
            $table_card_category = $stPostcardCard_model->prefix . 'st_postcard_category';
            $table_view_table = $stPostcardCard_model->prefix . 'st_postcard_view';
            $table_card_category = $stPostcardCard_model->prefix . 'st_postcard_category';

            $args['fields'] = array('card_user.name customer_name,card.name card_name, card.logo_file logo_url, card.*, table1.shared_email shared_email, table2.shared_fb shared_fb, (COALESCE(table1.shared_email,0) + COALESCE(table2.shared_fb,0)) shared, sum(card_view.number_view) viewed, card_category.title category_title');
            $extra_sql = "
            INNER JOIN $table_card_user card_user on card.user_id = card_user.id
            LEFT JOIN $table_card_category card_category on card_category.id = card.cat_id
            LEFT JOIN $table_view_table card_view on card_view.card_id = card.id
            LEFT JOIN
            (
            SELECT card.id id , sum(share.number_share) shared_email FROM {$card_table} card 
            LEFT JOIN {$card_share_table} share on share.card_id = card.id 
            WHERE `type_share` like('email') GROUP BY card.id
            ) table1 ON table1.id = card.id 
            LEFT JOIN
            (
            SELECT card.id id, sum(share.number_share) shared_fb FROM {$card_table} card 
            LEFT JOIN {$card_share_table} share on share.card_id = card.id 
            WHERE `type_share` like('facebook') GROUP BY card.id
            ) table2 ON table2.id = card.id 
            ";
            $args['group_by'] = 'card.id';
        } else {
            $table_card_category = $stPostcardCard_model->prefix . 'st_postcard_category';
            $card_table = $stPostcardCard_model->prefix . 'st_postcard_card';

            $args['fields'] = array('card.name card_name, card.logo_file logo_url, card.*, card_category.title category_title, count(card_1.template_id) nr_created');
            $extra_sql = "LEFT JOIN $table_card_category card_category on card_category.id = card.cat_id
            LEFT JOIN $card_table card_1 on card.id = card_1.template_id
            ";
            $args['group_by'] = 'card.id';
        }

        $objects = $stPostcardCard_model->getRecords($args, $extra_sql);
        $args['limit'] = array();
        //$object user for view dashboard postcard statistic 
        $object = $stPostcardCard_model->getRecords($args, $extra_sql);
        $total = $stPostcardCard_model->countRecords($args, $extra_sql);

        $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName);

        if(empty($arg['columns'])){
            if ($current_folder != $this->config['folder_template']) {
                $columns = array(
                    'card_name' => __('Name', $this->config['plugin_name']),
                    'category_title' => __('Category', $this->config['plugin_name']),
                    'customer_name' => __('Generated by', $this->config['plugin_name']),
    //                'file_name' => __('File name', $this->config['plugin_name']),
                    'thumb_url' => __('Front side', $this->config['plugin_name']),
                    'back_thumb_url' => __('Back side', $this->config['plugin_name']),
                    'viewed' => __('No. Views', $this->config['plugin_name']),
                    'shared' => __('No. Shares', $this->config['plugin_name']),
                    'shared_fb' => __('No. Facebook Shares', $this->config['plugin_name']),
                    'shared_email' => __('No. Email Shares', $this->config['plugin_name']),                
    //                'photographer' => __('Photographer', $this->config['plugin_name']),
                    'cdate' => __('Created <br/> &nbsp;date', $this->config['plugin_name'])
                );
            } else {
                $columns = array(
    //                'customer_name' => __('User name', $this->config['plugin_name']),
                    'card_name' => __('Name', $this->config['plugin_name']),
                    'category_title' => __('Category', $this->config['plugin_name']),
    //                'file_name' => __('File name', $this->config['plugin_name']),
                    'thumb_url' => __('Postcard front-side', $this->config['plugin_name']),
                    'logo_url' => __('Postcard logo', $this->config['plugin_name']),
                    'nr_created' => __('Times used', $this->config['plugin_name']),
                    'featured' => __('Featured', $this->config['plugin_name']),
    //                'photographer' => __('Photographer', $this->config['plugin_name']),
                    'cdate' => __('Created date', $this->config['plugin_name'])
                );
            }
        }else{
            $columns = $arg['columns'];
        }
        
        register_column_headers('stFacebookToolbox_stPostcards', $columns);

        $smt_user_id = $this->functions->getCurrentSmtUserId($this->config);
        $args = array();
        $args['where'] = " smt_user_id = $smt_user_id";
        $categories = $stPostcardCategory_model->getRecords($args);
        
        
        /////////////////
//        $this->view->headIcon = 'icon_re';
//        $this->view->headTitle1 = 'Postcards';
        $this->view->objects = $objects;
        $this->view->object = $object; //use in view dashboardPostcard
        $this->view->current_folder = $current_folder;
        $this->view->pagination = $pagination;
        $this->view->categories = $categories;
        $this->view->current_category_id = $current_category_id;
        $this->view->cur_page = $cur_page;
        $this->view->functions = $this->functions;
        $this->view->current_action1 = $current_action1;
        
        
    }
    private function getRandomString($length = 5) {

        $validCharacters = "ABCDEFGHIJKLMNPQRSTUXYVWZ123456789";

        $validCharNumber = strlen($validCharacters);

     

        $result = "";

     

        for ($i = 0; $i < $length; $i++) {

            $index = mt_rand(0, $validCharNumber - 1);

            $result .= $validCharacters[$index];

        }
        return $result;

    }
}

?>